Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Faster still:</p> <pre><code>public class ScratchPad { private static String a; public static void main( String[] args ) throws Exception { long time = System.currentTimeMillis(); StringBuilder sb = new StringBuilder( 128 ); for( int i = 0; i &lt; 10000000; i++ ) { // Resetting the string is faster than creating a new object. // Since this is a critical loop, every instruction counts. // sb.setLength( 0 ); sb.append( "someString" ); sb.append( "someString2" ); sb.append( "someStrin4g" ); sb.append( "someStr5ing" ); sb.append( "someSt7ring" ); setA( sb.toString() ); } System.out.println( System.currentTimeMillis()-time ); } private static void setA( String aString ) { a = aString; } } </code></pre> <p>In the philosophy of writing solid code, the inner workings of the method should be hidden from the objects that use the method. Thus it makes no difference from the system's perspective whether you redeclare the StringBuilder within the loop or outside of the loop. Since declaring it outside of the loop is faster, and it does not make the code more complicated to read, then reuse the object rather than reinstantiate it.</p> <p>Even if the code was more complicated, and you knew for certain that object instantiation was the bottleneck, comment it.</p> <p>Three runs with this answer:</p> <pre><code>$ java ScratchPad 1567 $ java ScratchPad 1569 $ java ScratchPad 1570 </code></pre> <p>Three runs with the other answer:</p> <pre><code>$ java ScratchPad2 1663 2231 $ java ScratchPad2 1656 2233 $ java ScratchPad2 1658 2242 </code></pre> <p>Although not significant, setting the <code>StringBuilder</code>'s initial buffer size will give a small gain.</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