Why is the format! macro slower than pushing into a String directly?

Viewed 519

When I was trying to generate a string, I used both format! and directly pushed into a String.

Pushing into a String directly took ~40 ns/iter while using format! took ~80 ns/iter (twice as long).

Why doesn't the compiler optimize format! to the fastest possible machine code? Maybe I'm wrong, but one of promises of format! is that it should produce the fastest possible code.

Is there a way to make format! produce a better code? Or there will always be a speed penalty when using it?

#![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) {
        b.iter(|| do_push("my_real_login", "with my real password"));
    }

    #[bench]
    fn bench_format(b: &mut Bencher) {
        b.iter(|| do_format("my_real_login", "with my real password"));
    }
}
0 Answers
Related