在Java中的循环混乱 [英] Confusion on loops in java

查看:116
本文介绍了在Java中的循环混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  a)for(int i = 100000; i> 0; i- - ){} 
b)for(int i = 1; i <100001; i ++){}



我一直在寻找答案,这是选项a,任何人的解释?任何帮助表示赞赏

解决方案

在Java中,反向循环可能会稍快一些。下面是一个示例基准测试 。通常,这些差异是通过增量/减量指令或循环终止比较指令中的实现细节来解释的,无论是在底层处理器架构的上下文中。在更复杂的示例中,反转循环可以帮助消除依赖关系,从而启用其他优化,或者可以提高内存局部性和缓存,甚至垃圾收集行为。



对于所有情况,任何一种循环总是会更快 - 需要一个基准来确定哪个循环在给定平台上表现更好,具体情况如何。而且我甚至没有考虑过JIT编译器要做什么。



无论如何,这是一种微观优化,可能使代码更难以阅读,没有提供显着的性能提升。所以,除非有必要,否则最好避免它们,记住 - 不成熟的优化是万恶之源。

Which one is faster in java ?

a)  for(int i = 100000; i > 0; i--) {}
b)  for(int i = 1; i < 100001; i++) {}

I have been looking for explanation to the answer which is option a, anyone? any help is appreciated

解决方案

There are situations when a reverse loop might be slightly faster in Java. Here's a benchmark showing an example. Typically, the difference is explained by implementation details in the increment/decrement instructions or in the loop-termination comparison instructions, both in the context of the underlying processor architecture. In more complex examples, reversing the loop can help eliminate dependencies and thus enable other optimizations, or can improve memory locality and caching, even garbage collection behavior.

One can not assume that either kind of loop will always be faster, for all cases - a benchmark would be needed to determine which one performs better on a given platform, for a concrete case. And I'm not even considering what the JIT compiler has to do with this.

Anyway, this is the sort of micro-optimizations that can make code more difficult to read, without providing a noticeable performance boost. And so it's better to avoid them unless strictly necessary, remember - "premature optimization is the root of all evil".

这篇关于在Java中的循环混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆