Closed
Description
For some reason, it seems that rustc can deduce .len() == 0
better for vec![]
than for Vec::new()
.
pub fn a() -> usize {
let v: Vec<u8> = Vec::new();
let mut v2: Vec<u8> = Vec::new();
if v.len() > 1 { // false
v2 = vec![2];
} else {
v2 = Vec::new();
}
v.len() + v2.len() // 0
}
example::a:
push rbx
sub rsp, 48
xorps xmm0, xmm0
movaps xmmword ptr [rsp + 32], xmm0
mov qword ptr [rsp + 8], 1
movups xmmword ptr [rsp + 16], xmm0
mov rsi, qword ptr [rsp + 16]
mov rbx, qword ptr [rsp + 24]
test rsi, rsi
je .LBB0_2
mov edi, 1
mov edx, 1
call __rust_dealloc@PLT
.LBB0_2:
mov rax, rbx
add rsp, 48
pop rbx
ret
https://rust.godbolt.org/z/xEhPhI
surprisingly, when I replaced one Vec::new()
with vec![]
, rustc was able to const-eval the return value to 0
.
pub fn a() -> usize {
let v: Vec<u8> = Vec::new();
let mut v2: Vec<u8> = Vec::new();
if v.len() > 1 { // false
v2 = vec![2];
} else {
v2 = vec![]; // I changed this
}
v.len() + v2.len() // 0
}
example::a:
xor eax, eax
ret
https://rust.godbolt.org/z/cdbEGU
Apparently
pub fn a() -> usize {
let v: Vec<u8> = vec![];
v.len()
}
and
pub fn a() -> usize {
let v: Vec<u8> = Vec::new();
v.len()
}
generate the same code tough.