函数调用的成本有多大?
因此,有两种情况:
情况 1:
if (doSomething) doFunction();
//...
void doFunction() {
// ... do something time consuming
}
情况 2:
doFunction();
//...
void doFunction() {
if (!doSomething) return;
// ... do something time consuming
}
这是在对时间极其敏感的环境中(大约 0.1 毫秒会产生很大的差异); doFunction()
被频繁调用(大约 100 次),并且大多数情况下,doSomething
为 false。显然,情况 1 会更有效,但效率是多少呢?或者它不会产生影响(大约 0.01 毫秒)?
So, two cases:
Case1:
if (doSomething) doFunction();
//...
void doFunction() {
// ... do something time consuming
}
Case 2:
doFunction();
//...
void doFunction() {
if (!doSomething) return;
// ... do something time consuming
}
This is within extremely time sensitive environment (roughly 0.1 ms would make a big difference); doFunction()
is called quite often (order of ~100 times) and most often than not, doSomething
is false. It seems obvious that case 1 would be more efficient, but by how much? Or would it not make a difference (on the order of 0.01 ms)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
情况 1 会更有效。差异的幅度很小;我们讨论的是一条指令和几条指令之间的区别 - 因此在任何每秒可以执行几百万条指令的机器上,这是微不足道的。
第一种情况(通常)由单个条件跳转指令实现。
在第二种情况下,除了条件跳转之外,函数调用的开销始终存在。
无论如何,编译器可能会优化第二种情况,使它们等效。您可以通过查看编译器输出或自行计时来进行检查。
Case 1 would be more efficient. The magnitude of the difference will be tiny; we're talking about the difference between one instruction and a couple of instructions - so on any machine that can do a few million instructions per second, that's insignificant.
The first case would (typically) be implemented by a single conditional jump instruction.
In the second case, the overhead of the function call is always present in addition to the conditional jump.
It may be the case that the compiler will optimize the second case anyway, making them equivalent. You can check by looking at the compiler output, or by timing it yourself.
函数调用涉及将内容放入堆栈帧,然后在调用 return 时将这些内容弹出。它们都涉及条件
jmp
(跳转),因此不会影响性能。我会采用第一种方法。A function call involves putting stuff on the stack frame, and later popping that stuff back off when you call return. Both of them involve a conditional
jmp
(jump), so that does not impact performance. I would go with the first approach.