Java Optimization with StringBuilder

The question keeps coming up: How do I optimize a Java application? It’s not a trivial question. One easy route is to limit unnecessary object instantiation. The biggest culprits here are String objects. Consider the following Java code snippet:

String test = "";
long start = System.currentTimeMillis();
for(int i = 0; i < 50000; i++) {
	test += "abc";
}
System.out.println("Time lapse using +=: " +
System.currentTimeMillis() - start) + " milliseconds";

This Java code just prints the time it takes to concatenate the string "abc" 50,000 times. The result on my system is:

Time lapse using +=: 11700 milliseconds

Now consider the following Java code snippet that uses StringBuilder to accomplish the same thing:

test = "";
start = System.currentTimeMillis();
StringBuilder builder = new StringBuilder();
for(int i = 0; i < 50000; i++) {
	builder.append("abc");
}
System.out.println("Time lapse using StringBuilder: " +
	(System.currentTimeMillis() - start) +
	" milliseconds");

The output from this code is:

Time lapse using StringBuilder: 0 milliseconds

Now that's what I call optimized Java code! Using the += operator to concatenate strings generates a new String object for each pass in the for loop plus another object to contain the new value. StringBuilder, on the other hand, buffers the process. That's just one example. There's lots more offered in the Java Performance Tuning course. Check it out.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.