Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is no point in doing so. Builtin types have no remarkable setup cost. </p> <p>The thing is different with objects.</p> <p>You should predeclare Objects outside the loop for performance reasons. I tested this with JDK 1.4, never again since then. Possibly newer JDKs will optimize this away.</p> <pre><code>for(int i=0;i&lt;2000;i++) for(int j=0;j&lt;1000;j++) String x = "Hello " + j; </code></pre> <p>is remarkably slower than (define outside loop)</p> <pre><code>String x; for(int i=0;i&lt;2000;i++) for(int j=0;j&lt;1000;j++) x = "Hello " + j; </code></pre> <p>is remarkably slower than (final in loop)</p> <pre><code>for(int i=0;i&lt;2000;i++) for(int j=0;j&lt;1000;j++) final String x = "Hello " + j; </code></pre> <p>update: just ran a timing with JDK 7u45, 1000 x 1000 iterations</p> <p>I have set the code to run the loops more than once and to keep the variables in a result array. Another run will not store the variables outside the loop. </p> <ul> <li>String allocation in loop and store in array: Avg 109.49 / NoGC: 47-49 (*)</li> <li><p>String allocation in loop and no store: Avg 43.5 / NoGC: 39-47</p></li> <li><p>String allocation outside loop and store in array: Avg 98.9 / NoGC: 42-44</p></li> <li><p>String allocation outside loop and no store: Avg 28.25 / NoGC: 27-32</p></li> <li><p>final String allocation in loop and store in array: Avg 98.92 / NoGC: 42-50</p></li> <li>final String allocation in loop and no store: Avg 28.31 / NoGC: 27-34</li> </ul> <p>The results show, that the declaration of the object takes it's toll. But the real driver is the GC. The effects of declaration inside the loop or outside are small over time, if the value is used outside the loop. Using a final String inside the loop will make no difference. If you do not store outside the loop, the difference is remarkable between the declaration of the variable inside the loop or outside, final, again, makes no difference.</p> <p>(* When storing all the values, most of the time was lost in GC runs, that is why I added the span of the runs without GC.)</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