Creating StringBuilder in Java

Posted by & filed under , , .

I wrote in my previous post about StringBuilder’s in Java, and I felt I should provide some measurements around the whole discussion. So I put together some quick and dirty code which is good enough for a comparison of the 2 ways of creating a StringBuilder — bear in mind I said “comparison”, as such timings are not necessarily accurate but they serve as a purpose to create the order of magnitude of the 2 methods!

If you look at the code below I’ve just put together just 2 functions: one that creates a StringBuilder using default constructor then appends 40 chars to it, and one that constructs the StringBuilder passing it the 40 chars as a String. Both functions return the time it took in nanos to complete this operation. I’ve wrapped all of this up in a for loop about 100,000 times — enough to eliminate any JVM “warm ups” and computed the average:

package liviutudor;
 
/**
 * Tests different ways of creating StringBuilder's.
 *
 * @author Liviu Tudor http://liviutudor.com
 */
public class StringBuilderTest {
	public static final String	CHARS = "0123456789012345678901234567890123456789";
	public static final int		TRIES = 100000;
 
	public static void main(String[] args) {
		double result = 0.0;
		for( int i = 0; i < TRIES; i++ ) {
			result += (double)createNoParams() / TRIES;
		}
		System.out.println( "Without parameters:" + result );
 
		result = 0.0;
		for( int i = 0; i < TRIES; i++ ) {
			result += (double)createParams() / TRIES;
		}
		System.out.println( "With parameters:" + result );
	}
 
	/**
	 * Creates a stringbuilder using default constructor.
	 * Then appends chars to it.
	 * @return time it took in nanoseconds
	 */
	public static long createNoParams() {
		long start = System.nanoTime();
		StringBuilder s = new StringBuilder();
		s.append( CHARS );
		return (System.nanoTime() - start);
	}
 
	/**
	 * Creates a stringbuilder using a String.
	 * @return time it took in nanoseconds
	 */
	public static long createParams() {
		long start = System.nanoTime();
		StringBuilder s = new StringBuilder(CHARS);
		return (System.nanoTime() - start);
 
	}
}

Now run this a few times and average the averages 🙂 and you’ll get something like this:

Without parameters:879.314880000076
With parameters:515.528040000167

So by not using the parametrized version, and constructing the builder first and then appending characters to it you spend about 40-50% more time in your code doing so!

I will probably come back at some point with some memory measurements too on this.

Leave a Reply

Your email address will not be published.