i
发布于 2024-11-09 00:04:19 字数 248 浏览 0 评论 0 原文

在较小程度上,如果 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
}

更新:
正如几乎每个人的建议,我运行了一个简单的测试,其中包含三个循环变化

And to a lesser extent, what about a for loop with i<(n+1)? Would (n+1) get evaluated once at start of loop or at every iteration?

for(int i=0; i<(n+1); i++){  
   // Do something
}

for(int i=0; i<=n; i++){  
   //Do something
}

UPDATE:
As suggested by nearly everyone, I ran a simple test with three loop variations i

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

护你周全 2024-11-16 00:04:19

这可能取决于 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.

丑疤怪 2024-11-16 00:04:19

我真的怀疑这会对循环执行产生可测量的差异。特别是 <<=。如果您真的担心,您应该衡量一下

I really doubt that would make a measurable difference in the loop execution. Particularly < vs <=. If you're really concerned, you should measure it.

梦中楼上月下 2024-11-16 00:04:19

这是编译器特定的,没有语言标准定义这一点,尽管大多数编译器会尝试缓存该值(如果它被证明是不变的)。

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).

灼疼热情 2024-11-16 00:04:19

相信编译器。尽管 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.

胡大本事 2024-11-16 00:04:19

(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文