当我尝试生成一个字符串时,我同时使用了两者format!并直接推入了String.
String直接推入 a需要 ~40 ns/iter,而 usingformat!需要 ~80 ns/iter(两倍长)。
为什么编译器不优化format!为最快的机器代码?也许我错了,但承诺之一format!是它应该生成最快的代码。
有没有办法使format!产生更好的代码?还是在使用时总会有速度损失?
#![feature(test)]
fn do_push(username: &str, password: &str) -> String {
let mut body = String::with_capacity(
"grant_type=password&username=".len()
+ username.len()
+ "&password=".len()
+ password.len(),
);
body.push_str("grant_type=password&username=");
body.push_str(username);
body.push_str("&password=");
body.push_str(password);
return body;
}
fn do_format(username: &str, password: &str) -> String {
format!(
"grant_type=password&username={}&password={}",
username, password
)
}
#[cfg(test)]
mod tests {
extern crate test;
use test::Bencher;
#[bench]
fn bench_push(b: &mut Bencher) …Run Code Online (Sandbox Code Playgroud)