Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do empty functions get optimized away in Rust?

I want to put some performance impacting function calls behind a feature gate in my code. If the feature isn't enabled, I was thinking of just having an empty implementation of that function implemented instead. That way, hopefully, the Rust complier can completely remove that from the function.

Something like this:

// Included if feature is enabled
fn foo() {
    // ...
}

// Included if the feature is disabled
fn foo() {}

// Performance critical code
for i in 1..1000000000 {
    // ...
    foo();
}

Would the call to foo() get optimized away if it is empty?

like image 779
Sunjay Varma Avatar asked Feb 04 '23 17:02

Sunjay Varma


1 Answers

Just try it in the amazing Compiler Explorer :)

The result assembly for your example is:

example::main:
    push    rbp
    mov     rbp, rsp
    mov     eax, 1
.LBB0_1:
    xor     ecx, ecx
    cmp     eax, 1000000000
    setl    cl
    add     ecx, eax
    cmp     eax, 1000000000
    mov     eax, ecx
    jl      .LBB0_1
    pop     rbp
    ret

As you can see there is no call instruction and foo() isn't called at all. However, you might wonder why the loop isn't removed, as it doesn't have an effect on the outside world. I can just assume that sometimes those loops are in fact used to waste time in some sense. If you decrease the counter to 100, the loop is completely removed.

Anyway: Yes, the optimizer will remove empty functions!

like image 110
Lukas Kalbertodt Avatar answered Feb 08 '23 16:02

Lukas Kalbertodt