Description
I tried this code:
pub fn a() -> String {
String::new()
}
pub fn b() -> String {
"".to_string()
}
I expected to see this happen: both functions contain identical code.
Instead, this happened: https://rust.godbolt.org/z/P53MMG4W6.
For String::new()
it does one more instruction: mov rcx, qword ptr [rip + .L__unnamed_1]
. This rcx
is then read further below at mov qword ptr [rdi], rcx
.
The "".to_string()
version however does not do this extra step and immediately reads from a constant: mov qword ptr [rdi], 1
.
This means that String::new()
does slightly more work than "".to_string()
but I expect them to be identical.
Before 1.52.0 the functions generated identical code: https://rust.godbolt.org/z/8647E6YhY.
oli noted the following:
The problem is probably because it copies its value from the constant
instead of immediately creating the appropriate valuerust/library/alloc/src/raw_vec.rs
Line 64 in d620ae1
Meta
This currently happens on nightly.