Is it better to reuse a StringBuilder in a loop?

前端 未结 14 2058
名媛妹妹
名媛妹妹 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:31

    The modern JVM is really smart about stuff like this. I would not second guess it and do something hacky that is less maintainable/readable...unless you do proper bench marks with production data that validate a non-trivial performance improvement (and document it ;)

    0 讨论(0)
  • 2020-12-04 07:32

    Not significantly faster, but from my tests it shows on average to be a couple millis faster using 1.6.0_45 64 bits: use StringBuilder.setLength(0) instead of StringBuilder.delete():

    time = System.currentTimeMillis();
    StringBuilder sb2 = new StringBuilder();
    for (int i = 0; i < 10000000; i++) {
        sb2.append( "someString" );
        sb2.append( "someString2"+i );
        sb2.append( "someStrin4g"+i );
        sb2.append( "someStr5ing"+i );
        sb2.append( "someSt7ring"+i );
        a = sb2.toString();
        sb2.setLength(0);
    }
    System.out.println( System.currentTimeMillis()-time );
    
    0 讨论(0)
提交回复
热议问题