Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Sorry to say, but @Jigar's answer is incorrect. This is the correct answer. (tldr; don't use <code>for : each</code>).</p> <pre><code>import java.util.ArrayList; import java.util.List; public class LoopTest { public static void main(String s[]) { long start, end; List&lt;Integer&gt; a = new ArrayList&lt;Integer&gt;(); for (int i = 0; i &lt; 2500000; i++) { a.add(i); } ///// TESTING FOR : EACH LOOP start = System.currentTimeMillis(); for (Integer j : a) { int x = j + 3; } end = System.currentTimeMillis(); System.out.println(end - start + " milli seconds for [ Integer j : a ] "); ////// TESTING DEFAULT LOOP start = System.currentTimeMillis(); for (int i = 0; i &lt; a.size(); i++) { int x = a.get(i) + 3; } end = System.currentTimeMillis(); System.out.println(end - start + " milli seconds for [ int i = 0; i &lt; a.length; i++ ] "); ////// TESTING SLIGHTLY OPTIMIZED LOOP start = System.currentTimeMillis(); int size = a.size(); for (int i = 0; i &lt; size; i++) { int x = a.get(i) + 3; } end = System.currentTimeMillis(); System.out.println(end - start + " milli seconds for [ int i = 0; i &lt; size; i++ ] "); //// TESTING MORE OPTIMIZED LOOP start = System.currentTimeMillis(); for (int i = size; --i &gt;= 0;) { int x = a.get(i) + 3; } end = System.currentTimeMillis(); System.out.println(end - start + " milli seconds for [ int i = size; --i &gt;= 0; ] "); } } </code></pre> <p>The results:</p> <pre><code>96 milli seconds for [ Integer j : a ] 57 milli seconds for [ int i = 0; i &lt; a.length; i++ ] 31 milli seconds for [ int i = 0; i &lt; size; i++ ] 31 milli seconds for [ int i = size; --i &gt;= 0; ] </code></pre> <p>You can make up your own mind, but too much attribution is given to the JVM optimizer. You still have to be smart with your own code, and using <code>for : each</code> notation is NOT a good idea (almost ever). As you can see, you have a good idea by putting size in its own variable.</p> <p>Even though some of these optimization may be JVM-dependent (and some may kick in with the JIT), it's important to know what Java does and what Java doesn't do.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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