i
在较小程度上,如果 i<(n+1) 的 for 循环又如何呢? (n+1) 会在循环开始时或每次迭代时计算一次吗?
for(int i=0; i<(n+1); i++){
// Do something
}
for(int i=0; i<=n; i++){
//Do something
}
更新:
正如几乎每个人的建议,我运行了一个简单的测试,其中包含三个循环变化
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web
技术交流群。
在较小程度上,如果 i<(n+1) 的 for 循环又如何呢? (n+1) 会在循环开始时或每次迭代时计算一次吗?
for(int i=0; i<(n+1); i++){
// Do something
}
for(int i=0; i<=n; i++){
//Do something
}
更新:
正如几乎每个人的建议,我运行了一个简单的测试,其中包含三个循环变化
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这可能取决于 n 的值在循环过程中是否发生变化。如果没有,我认为任何现代编译器都会缓存 n+1 的值,而不是每次迭代都计算它。当然,这并不能保证,并且在没有优化的情况下,每次都会评估 n+1 。
编辑:要回答标题问题,我< n 与 i <= n 没有明显差异(除了额外的迭代,假设两种情况下 n 相等。)CPU 对于这两种比较都有单一操作。
It would likely depend on whether or not the value of n was changing over the course of the loop. If not, I would think that any modern compiler would cache the value of n+1, rather than calculating it each iteration. Of course that's not a guarantee, and with no optimizations, n+1 would be evaluated each time.
EDIT: To answer the title question, i < n vs. i <= n would have no noticeable difference (other than an extra iteration, assuming the n's were equal in both cases.) CPUs have single ops for both comparisons.
我真的怀疑这会对循环执行产生可测量的差异。特别是
<
与<=
。如果您真的担心,您应该衡量一下。I really doubt that would make a measurable difference in the loop execution. Particularly
<
vs<=
. If you're really concerned, you should measure it.这是编译器特定的,没有语言标准定义这一点,尽管大多数编译器会尝试缓存该值(如果它被证明是不变的)。
This is compiler specific, no language standard defines this, though most compilers would try to cache the value (if it's proven to be invariant).
相信编译器。尽管 c# 编译器 + JITer 不如最好的 c++ 编译器,但它仍然相当不错。除非您使用分析器确定它导致了问题,否则您不应该花时间担心这些类型的微观优化。相反,写下逻辑上与你正在做的事情相匹配的内容。
Trust the compiler. Even though the c# compiler + JITer is not as good as the best c++ compilers it is still pretty good. Unless you determine with a profiler that it is causing a problem you shouldn't spend cycles worrying about these sorts of micro-optimizations. Instead write what logically matches what you are doing.
(n+1)
将在每次迭代时进行评估,假设它没有被编译器优化。至于性能问题 - 使用 自行测量非常容易
StopWatch
类。我猜除非你的 i 非常高,否则差异可以忽略不计。
(n+1)
will get evaluated on very iteration, assuming it doesn't get optimized out by the compiler.As for performance issues - this is very easy to measure for yourself using the
StopWatch
class.I would guess that unless your
i
is very high, the differences would be negligible.