Loop counter in Java API

后端 未结 3 1845
野趣味
野趣味 2020-12-01 22:36

All,

While going through some of the files in Java API, I noticed many instances where the looping counter is being decremented rather than increment. i.e. in

3条回答
  •  日久生厌
    2020-12-01 23:09

    It is possible that this is a result of Sun engineers doing a whole lot of profiling and micro-optimization, and those examples that you found are the result of that. It is also possible that they are the result of Sun engineers "optimizing" based on deep knowledge of the JIT compilers ... or based on shallow / incorrect knowledge / voodoo thinking.

    It is possible that these sequences:

    • are faster than the increment loops,
    • are no faster or slower than increment loops, or
    • are slower than increment loops for the latest JVMs, and the code is no longer optimal.

    Either way, you should not emulate this practice in your code, unless thorough profiling with the latest JVMs demonstrates that:

    • your code really will benefit from optimization, and
    • the decrementing loop really is faster than the incrementing loop for your particular application.

    And even then, you may find that your carefully hand optimized code is less than optimal on other platforms ... and that you need to repeat the process all over again.

    These days, it is generally recognized that the best first strategy is to write simple code and leave optimization to the JIT compiler. Writing complicated code (such as loops that run in reverse) may actually foil the JIT compiler's attempts to optimize.

提交回复
热议问题