不确定我的措辞是否正确,但要点是:
调用 math.Pow(x, 2)
是否更有效,还是应该使用 x*x
?
我已经尝试过它们,但不幸的是,我无法检测到我的测试文件中可能存在的微秒差异。
最佳答案
通常函数调用需要一些额外的时间(例如,传递参数并将其返回到函数或从函数返回)。但对于简单的情况,Go 可以进行一些优化,例如内联。 如文档CompilerOptimizations中所述有几个条件:
Only short and simple functions are inlined. To be inlined a function must conform to the rules:
- function should be simple enough, the number of AST nodes must less than the budget (80);
- function doesn't contain complex things like closures, defer, recover, select, etc;
- function isn't prefixed by go:noinline; function isn't prefixed by go:uintptrescapes,
- since the escape information will be lost during inlining;
- function has body; etc.
- gc: 1.0+
- gccgo: -O1 and above.
关于performance - 调用库和直接操作效率有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76895494/