我想在代码中的功能门后面放置一些影响函数调用的性能.如果没有启用该功能,我想的是只是实现了该功能的空实现.这样,希望Rust编译器可以完全从函数中删除它.
像这样的东西:
// Included if feature is enabled
fn foo() {
// ...
}
// Included if the feature is disabled
fn foo() {}
// Performance critical code
for i in 1..1000000000 {
// ...
foo();
}
Run Code Online (Sandbox Code Playgroud)
如果foo()是空的,那么对foo()的调用是否会被优化掉?
只需在惊人的编译器资源管理器中尝试:)
您的示例的结果程序集是:
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
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,没有任何call指令,foo()根本没有被调用.但是,您可能想知道为什么不删除循环,因为它对外界没有影响.我可以假设有时这些循环实际上用于在某种意义上浪费时间.如果减少计数器100,则完全删除循环.
无论如何:是的,优化器将删除空函数!