Is it better to reuse a StringBuilder in a loop?

前端 未结 14 2061
名媛妹妹
名媛妹妹 2020-12-04 06:46

I\'ve a performance related question regarding use of StringBuilder. In a very long loop I\'m manipulating a StringBuilder and passing it to another method like

14条回答
  •  失恋的感觉
    2020-12-04 07:24

    Faster still:

    public class ScratchPad {
    
        private static String a;
    
        public static void main( String[] args ) throws Exception {
            final long time = System.currentTimeMillis();
    
            // Pre-allocate enough space to store all appended strings.
            // StringBuilder, ultimately, uses an array of characters.
            final StringBuilder sb = new StringBuilder( 128 );
    
            for( int i = 0; i < 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( final String aString ) {
            a = aString;
        }
    }
    

    In the philosophy of writing solid code, the inner workings of the method are hidden from the client objects. Thus it makes no difference from the system's perspective whether you re-declare 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 significantly more complicated, reuse the object.

    Even if it was much more complicated, and you knew for certain that object instantiation was the bottleneck, comment it.

    Three runs with this answer:

    $ java ScratchPad
    1567
    $ java ScratchPad
    1569
    $ java ScratchPad
    1570
    

    Three runs with the other answer:

    $ java ScratchPad2
    1663
    2231
    $ java ScratchPad2
    1656
    2233
    $ java ScratchPad2
    1658
    2242
    

    Although not significant, setting the StringBuilder's initial buffer size, to prevent memory re-allocations, will give a small performance gain.

提交回复
热议问题