Nov
05
2009
0

Java String Performance

I have know for a long time that the + operation for Strings in Java is horrible for performance. Because Strings are immutable in Java another String object is created for each +, not so good! I did notice the other day that there is a String.concat() operation. I wondered if it would run faster then + or even as fast as a StringBuilder. The following is the test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Date;
class st{
	public static void main(String args[]){
		// Test the + operator. We know this one is bad.
		// Its good to know its still bad in Java6
		long t = new Date().getTime();
		String x="";
		for(int i=0;i<100000;i++)
			x = x + " ";
		long e = new Date().getTime();
		System.out.println("Time to use the + operations on a string: " + (e-t));
 
		// Test the String.concat method. 
		// Is it any faster?
		t=new Date().getTime();
		x="";
		for(int i=0;i<100000;i++)
			x = x.concat(" ");
		e=new Date().getTime();
		System.out.println("Time to use the concat method on a string: " + (e-t));
 
		// Finaly out baseline. We know StringBuilder is(was)
		// the fastest way to build Strings.
		t=new Date().getTime();
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<100000;i++)
			sb.append(" ");
		String xx=sb.toString();
		e=new Date().getTime();
		System.out.println("Time to use a StringBuilder object: " + (e-t));
	}
}

And the results are!

abc:~ def$ java -version
java version "1.6.0_15"
Java(TM) SE Runtime Environment (build 1.6.0_15-b03-219)
Java HotSpot(TM) 64-Bit Server VM (build 14.1-b02-90, mixed mode)
abc:~ def$ javac st.java
abc:~ def$ java st
Time to use the + operations on a string: 29464
Time to use the concat method on a string: 7075
Time to use a StringBuilder object: 2
abc:~ def$

So, what did we learn?

  • The + operator and Strings is still BAD!
  • The concat method is MUCH faster then the + operator
  • The StringBuilder is still the fastest method to create a String in Java
  • VN:F [1.9.3_1094]
    Rating: 0.0/10 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)
    Written by GreenO in: Technobabble | Tags: ,

    Powered by WordPress | Aeros Theme | TheBuckmaker.com WordPress Themes