From https://github.com/rust-lang/rust/pull/52805#discussion_r205945647. String::new() is faster than ""::to_string()
#[bench]
fn bench_string_new(b: &mut Bencher) {
b.iter(|| String::new());
}
#[bench]
fn bench_to_string(b: &mut Bencher) {
b.iter(|| "".to_string());
}
running 2 tests
test tests::bench_string_new ... bench: 0 ns/iter (+/- 0)
test tests::bench_to_string ... bench: 8 ns/iter (+/- 0)
The lint should probably also catch String::from("")
test tests::bench_string_from ... bench: 11 ns/iter (+/- 0)
test tests::bench_string_new ... bench: 0 ns/iter (+/- 0)
test tests::bench_to_string ... bench: 11 ns/iter (+/- 2)
as well as "".into::<String>()
Hm, interestingly, when looking in godbolt print!("{}", String::new()); seems to generate more instructions than print!("{}", "");
Probably because String::new() is of type String and "" is of type &str
I vote for slow_empty_string_creation as the name.
The suggestions of useless_format should to be changed as well.
warning: useless use of `format!`
--> src/main.rs:2:13
|
2 | let _ = format!("");
| ^^^^^^^^^^^ help: consider using .to_string(): `"".to_string()`
|
= note: #[warn(useless_format)] on by default
Should this lint be written as PreExpansionPass?
We should just fix this in liballoc instead.
That seems like a preferable solution. If the allocation is fixed, this could still be a style lint.
Most helpful comment
We should just fix this in liballoc instead.