Skip to main content

Why is String concatenation so slow??

3 replies [Last post]
ceklock
Offline
Joined: 2010-04-20
Points: 0

Today I was testing the time that it takes to concatenate strings 1 million times and I got shocked!

I was expecting that the concatenation without using StringBuilder would be slow, but not so slow!

While the first code below took only 25 miliseconds to run, the second I left running for more than 10 minutes and it did not finish! Weird!

1. StringBuilder builder = new StringBuilder();
2. for (int i = 0; i < 1000000; i++) {
3. builder.append("0");
4. }

1. String s = "";
2. for (int i = 0; i < 1000000; i++) {
3. s = s + "0";
4. }

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
wingetr
Offline
Joined: 2004-01-19
Points: 0

If you want to speed it up more, then include a capacity in the StringBuilder's constructor.

StringBuilder builder = new StringBuilder(1000000);
for(int i = 0; i < 1000000; i++)
{
builder.append("0");
}

Whenever you append something to a StringBuilder which doesn't fit in its capacity, it must create a new char array and copy its old value to the new place. If you know the resulting String will be 1000000 characters long, specify it so your program won't waste time allocating larger arrays.

walterln
Offline
Joined: 2007-04-17
Points: 0

Because the second is equivalent to:
[code]String s = "";
for (int i = 0; i < 1000000; i++) {
s = new StringBuilder(s).append("0").toString();
}
[/code]
which means there are a lot of objects created and a lot of copying of char arrays.

ceklock
Offline
Joined: 2010-04-20
Points: 0

I can't understand why this code is much faster:

001..public static String concat1(String s1, String s2, String s3,
002..String s4, String s5, String s6) {
003......String result = "";
004......result += s1;
005......result += s2;
006......result += s3;
007......result += s4;
008......result += s5;
009......result += s6;
010......return result;
011..}
012..
013..private static void stringTest() {
014......for (int i = 0; i < 1000000; i++) {
015..........concat1("a", "b", "c", "d", "e", "f");
016......}
017..}

I found the code of concat1() in the article "Becoming a Better Programmer: A Conversation With Java Champion Heinz Kabutz" (java.sun.com developer technicalArticles Interviews community kabutz_qa.html)

In this article the author is explaining that the code is more legible if you simply use the + operator, but he forgot to mention that there are cases where is simply impossible to use it because the performance is so slow that will block your program.

Message was edited by: ceklock