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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With