Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>An optimization trick that makes your code easier to maintain and less susceptible to a concurrency bug.</p> <pre><code>public class Slow { /** Loop counter; initialized to 0. */ private long i; public static void main( String args[] ) { Slow slow = new Slow(); slow.run(); } private void run() { while( i++ &lt; 10000000000L ) ; } } </code></pre> <p>$ time java Slow<br /> real 0m15.397s<br /> $ time java Slow<br /> real 0m20.012s<br /> $ time java Slow<br /> real 0m18.645s<br /></p> <p><strong>Average: 18.018s</strong></p> <pre><code>public class Fast { /** Loop counter; initialized to 0. */ private long i; public static void main( String args[] ) { Fast fast = new Fast(); fast.run(); } private void run() { long i = getI(); while( i++ &lt; 10000000000L ) ; setI( i ); } private long setI( long i ) { this.i = i; } private long getI() { return this.i; } } </code></pre> <p>$ time java Fast<br /> real 0m12.003s<br /> $ time java Fast<br /> real 0m9.840s<br /> $ time java Fast<br /> real 0m9.686s<br /></p> <p><strong>Average: 10.509s</strong></p> <p>It requires more bytecodes to reference a class-scope variable than a method-scope variable. The addition of a method call prior to the critical loop adds little overhead (and the call might be inlined by the compiler anyway).</p> <p>Another advantage to this technique (always using accessors) is that it eliminates a potential bug in the <strong>Slow</strong> class. If a second thread were to continually reset the value of <strong>i</strong> to 0 (by calling <code>slow.setI( 0 )</code>, for example), the <strong>Slow</strong> class could never end its loop. Calling the accessor and using a local variable eliminates that possibility.</p> <p>Tested using J2SE 1.6.0_13 on Linux 2.6.27-14.</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