Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>All these loops do the exact same, I just want to show these before throwing in my two cents.</p> <p>First, the classic way of looping through List:</p> <pre><code>for(int i=0;i&lt;strings.size();i++) { /* do something using strings.get(i) */ } </code></pre> <p>Second, the preferred way since it's less error prone (how many times have YOU done the "oops, mixed the variables i and j in these loops within loops" thing?).</p> <pre><code>for(String s : strings) { /* do something using s */ } </code></pre> <p>Third, the micro-optimized for loop:</p> <pre><code>int size = strings.size(); for(int i=0;++i&lt;=size;) { /* do something using strings.get(i) */ } </code></pre> <p>Now the actual two cents: At least when I was testing these, the third one was the fastest when counting milliseconds on how long it took for each type of loop with a simple operation in it repeated a few million times - this was using Java 5 with jre1.6u10 on Windows in case anyone is interested.</p> <p>While it at least seems to be so that the third one is the fastest, you really should ask yourself if you want to take the risk of implementing this peephole optimization everywhere in your looping code since from what I've seen, actual looping isn't usually the most time consuming part of any real program (or maybe I'm just working on the wrong field, who knows). And also like I mentioned in the pretext for the Java <em>for-each loop</em> (some refer to it as <em>Iterator loop</em> and others as <em>for-in loop</em>) you are less likely to hit that one particular stupid bug when using it. And before debating how this even can even be faster than the other ones, remember that javac doesn't optimize bytecode at all (well, nearly at all anyway), it just compiles it.</p> <p>If you're into micro-optimization though and/or your software uses lots of recursive loops and such then you may be interested in the third loop type. Just remember to benchmark your software well both before and after changing the for loops you have to this odd, micro-optimized one.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload