“计数限制”是否会被限制? for 循环的表达式仅计算一次,还是每次迭代?
如果我在循环的条件语句中调用一个方法,它会在每次循环迭代时被调用吗?
例如:
for( int i = 0; i <= expensiveComputation(); i++ ) {
// Do something.
}
我会在每次迭代中执行expenseComputation()
吗?或者在循环变量初始化的同时,expenseComputation()
的结果是否会在每次迭代中存储和使用?
我应该将其重写为:
int max = expensiveComputation();
for ( int i = 0; i <= max; i++ ) {
// Do something.
}
If I invoke a method within a loop's conditional statement, will it be called with each loop iteration?
For example:
for( int i = 0; i <= expensiveComputation(); i++ ) {
// Do something.
}
Will I be performing expensiveComputation()
on each iteration? Or will the result of expensiveComputation()
be stored and used in each iteration at the same time the loop variable is initialised?
Should I instead re-write it to that:
int max = expensiveComputation();
for ( int i = 0; i <= max; i++ ) {
// Do something.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它将在每次迭代时调用,除非编译器/优化器确定它没有副作用并且可以作为优化消除调用。
我的意思是,编译器不能盲目地存储值,因为 java 中的函数与数学函数不同,不仅可以有返回值,还可以有诸如将某些内容打印到某些流或更改某些全局状态等副作用。
还有另一个原因导致编译器无法省略每次迭代的调用。您的函数不接受任何参数这一事实并不意味着它每次都必须返回相同的值。例如,它可以从流中输入一个数字并返回它,或者它可以随机生成一个数字。
因此编译器需要非常小心才能安全地消除调用。所以,如果这个函数很昂贵,你一定应该预先存储它的值。
It will be invoked on each iteration, unless the compiler/optimizer decides that it has no side effects and can possibly eliminate the call as an optimization.
I mean, the compiler can't just blindly store the value because a function in java, unlike a mathematical function, can have not only a return value, but also such side effects as printing something to some stream or changing some global state etc.
There is also another reason why the compiler can't omit the call each iteration. The fact that your function doesn't take any arguments does not mean that it will necessarily return the same value each time. It can, for example, input a number from a stream and return it, or it can randomly generate a number.
So the compiler needs to be extremely careful before it can safely eliminate the calls. So, if the function is expensive, you should definitely pre-store its value.
如果不需要在每次迭代时进行计算,第二个选项会更好
如果你假设你的循环长度是 n 并且你的计算是 O(n)。
第一个解决方案的复杂度为 O(n2),而另一个解决方案的复杂度为 O(2n)
The second option is better specially if the computation does not require to be calculated at each iteration
If you suppose your loop is n length and you computation is O(n).
With the first solution, the complexity is O(n2) while the other is O(2n)
每次迭代可能会或可能不会调用它,具体取决于编译器想要发出的字节码。实际上很可能每次都会调用它。如果您想确保每次迭代时都不会调用它,请使用
int max = ...
版本。为什么不直接自己测试一下呢?
It may or may not be called on each iteration, depending on what bytecode the compiler feels like emitting.Most likely it will in fact be called each time.If you want to ensure that it is not invoked on each iteration, then use the
int max = ...
version.Why not simply test it yourself?
是的,在这些情况下您应该缓存结果,以确保更好的性能。
yes, you should cache your result in these situations, to ensure better performance.