Skip to content

const eval Vec::new() the same as vec![] #54475

Closed
@matthiaskrgr

Description

@matthiaskrgr

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.I-slowIssue: Problems and improvements with respect to performance of generated code.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions