Results 1 to 6 of 6
  1. #1
    stchman's Avatar
    stchman is offline Member
    Join Date
    Apr 2011
    Location
    Saint Louis, Missouri
    Posts
    97
    Rep Power
    0

    Default String concatenation vs. StringBuilder.

    Indeed the StringBuilder class is FAR faster for VERY LONG Strings.

    I have created code to time the two below:
    Java Code:
    public class StringStuff {
        public static void main( String[] args ) {
            StringStuff m = new StringStuff();
            m.addStrings();
        }
        
        public void addStrings() {    
            int i, j;
            int numberStrings = 100000;
            long initTime, finalTime;
            double totalTime;
            
            System.out.println( "Using String concatenation" );
            String str = "Test";
            // set initial time
            initTime = System.currentTimeMillis();
            for( i = 0; i < numberStrings; i++ ) {
                str += "A";
            }
            // set final time
            finalTime = System.currentTimeMillis();
            totalTime = (double)( finalTime - initTime ) / 1000.0;
            System.out.printf( "Total time to concatenate %d Strings using String concatenation is %f sec\n", i, totalTime );
            
            System.out.println( "Using StringBuilder class" );
            String stp = "Test";
            StringBuilder sb = new StringBuilder();
            stp = sb.append( stp ).toString();
            // set initial time
            initTime = System.currentTimeMillis();
            for( j = 0; j < numberStrings; j++ ) {
                stp = sb.append( "A" ).toString();
            }
            finalTime = System.currentTimeMillis();
            totalTime = (double)( finalTime - initTime ) / 1000.0;
            System.out.printf( "Total time to concatenate %d Strings using StringBuilder class is %f sec\n", i, totalTime );        
        }    
    }
    For 100000 Strings, the times on my PC are as follows:
    String concatenation = 21.5sec
    StringBuilder = 5.6sec

    With all this being said, I only started to see time differences when I got to 15000 or better. Even at 15K the times were as follows:
    String concatenation = 0.48sec
    StringBuilder = 0.13sec
    If you aren't programming in Java, well that's just too bad.
    I'd rather be using Ubuntu.

  2. #2
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

    Default

    Those timings don't include the extra work required by the JVM. For example, at some point in time all those extra String will need to be garbage collected.

    Also, your StringBuffer code test doesn't look fair because you a creating a new String every time. There is no need for the toString() to be invoked during every append() operation. The toString() method should only be invoked after the loop has finished executing.

    The general rule is to write readable code and only worry about performance when it is an issue. For my two cents I like the append() method anyway.

  3. #3
    stchman's Avatar
    stchman is offline Member
    Join Date
    Apr 2011
    Location
    Saint Louis, Missouri
    Posts
    97
    Rep Power
    0

    Default

    Excellent, I amended the program as follows:

    Java Code:
    public class StringStuff {
        public static void main( String[] args ) {
            StringStuff m = new StringStuff();
            m.addStrings();
            System.out.println( args.length );
        }
        
        public void addStrings() {    
            int i, j;
            int numberStrings = 100000;
            long initTime, finalTime;
            double totalTime;
            
            System.out.println( "Using String concatenation" );
            String str = "Test";
            // set initial time
            initTime = System.currentTimeMillis();
            for( i = 0; i < numberStrings; i++ ) {
                str += "A";
            }
            // set final time
            finalTime = System.currentTimeMillis();
            totalTime = (double)( finalTime - initTime ) / 1000.0;
            System.out.printf( "Total time to concatenate %d Strings using String concatenation is %f sec\n", i, totalTime );
            
            System.out.println( "Using StringBuilder class" );
            String stp = "Test";
            StringBuilder sb = new StringBuilder();
            stp = sb.append( stp ).toString();
            // set initial time
            initTime = System.currentTimeMillis();
            for( j = 0; j < numberStrings; j++ ) {
                sb.append( "A" );
            }
            stp = sb.toString();
            finalTime = System.currentTimeMillis();
            totalTime = (double)( finalTime - initTime ) / 1000.0;
            System.out.printf( "Total time to concatenate %d Strings using StringBuilder class is %f sec\n", i, totalTime );        
        }    
    }
    Using String concatenation still took ~21 secs, but the StringBuilder was near instantaneous.

    Thanks!!!!
    If you aren't programming in Java, well that's just too bad.
    I'd rather be using Ubuntu.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,792
    Rep Power
    19

    Default

    It's worth bearing in mind that single statement concatenation should be the same as, under the hood, the compiler uses a StringBuilder to do the work.
    So the following two should be pretty similar (and the former is easier to read):
    Java Code:
    String oneLine = "This is my String. " + anotherString + andAnother + " some more text " + lastBit;
    ...
    String theOtherLine = new StringBuilder().append("This is my String. ").append(anotherString).append(andAnother).append(" some more text ").append(lastBit).toString();
    (Hopefully that'll compile...)

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Tolls View Post
    It's worth bearing in mind that single statement concatenation should be the same as, under the hood, the compiler uses a StringBuilder to do the work.
    So the following two should be pretty similar (and the former is easier to read):
    Java Code:
    String oneLine = "This is my String. " + anotherString + andAnother + " some more text " + lastBit;
    ...
    String theOtherLine = new StringBuilder().append("This is my String. ").append(anotherString).append(andAnother).append(" some more text ").append(lastBit).toString();
    (Hopefully that'll compile...)
    It does ;-) Also note that the following variation of your code:

    Java Code:
    	  String oneLine = "This is my String. "; 
    		  oneLine+= anotherString; 
    		  oneLine+= andAnother;
    		  oneLine+= " some more text ";
    		  oneLine+= lastBit;
    ... creates a new StringBuilder for every single String catenation operation.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,792
    Rep Power
    19

    Default

    Oh yes.
    That's one of the things those code checkers tend to throw up.

Similar Threads

  1. Concatenation with strings
    By link6790 in forum New To Java
    Replies: 16
    Last Post: 05-05-2011, 07:33 PM
  2. Replies: 4
    Last Post: 08-19-2010, 01:06 AM
  3. Concatenation file contents
    By Java Tip in forum Java Tip
    Replies: 1
    Last Post: 02-07-2008, 01:29 PM
  4. Database Column vs String Concatenation
    By varun_33 in forum JDBC
    Replies: 1
    Last Post: 12-11-2007, 04:14 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •