Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to concatenate two Strings in Java?

What's the fastest way to concatenate two Strings in Java?

i.e

String ccyPair = ccy1 + ccy2; 

I'm using cyPair as a key in a HashMap and it's called in a very tight loop to retrieve values.

When I profile then this is the bottleneck

java.lang.StringBuilder.append(StringBuilder.java:119)   java.lang.StringBuilder.(StringBuilder.java:93) 
like image 611
Dan Avatar asked Feb 22 '11 10:02

Dan


1 Answers

Lots of theory - time for some practice!

private final String s1 = new String("1234567890"); private final String s2 = new String("1234567890"); 

Using plain for loops of 10,000,000, on a warmed-up 64-bit Hotspot, 1.6.0_22 on Intel Mac OS.

eg

@Test public void testConcatenation() {     for (int i = 0; i < COUNT; i++) {         String s3 = s1 + s2;     } } 

With the following statements in the loops

String s3 = s1 + s2;  

1.33s

String s3 = new StringBuilder(s1).append(s2).toString(); 

1.28s

String s3 = new StringBuffer(s1).append(s2).toString(); 

1.92s

String s3 = s1.concat(s2); 

0.70s

String s3 = "1234567890" + "1234567890"; 

0.0s

So concat is the clear winner, unless you have static strings, in which case the compiler will have taken care of you already.

like image 71
Duncan McGregor Avatar answered Sep 21 '22 08:09

Duncan McGregor