Java String Concatenation

March 15, 2007

I was having a discussion with a co-worker today regarding String concatenation in Java. Somewhere along the line, I was told that the Java + operator, when applied to String, was slow when compared to using the append method of StringBuffer or StringBuilder. Tuns out this is a myth, sort of. I wrote a class to test it. This will first concatenate a String 100 times using the + operator, and then build the same string using StringBuilder's append method:

public class StringTest {

    private int iterations;

    public static void main(String[] args) {
        StringTest test = new StringTest(100);
        for(int i = 0; i < 10; i++) {
            test.concat();
            test.append();
        }
    }

    public StringTest(int iterations) {
        this.iterations = iterations;
    }

    private void concat() {
        String foo = "";
        long start = System.currentTimeMillis();
        for(int i = 0; i < iterations; i++) {
            foo += "foo";
        }
        System.out.println("String concat took "+(System.currentTimeMillis()-start)+" ms");
    }

    private void append() {
        StringBuilder sb = new StringBuilder();
        long start = System.currentTimeMillis();
        for(int i = 0; i < iterations; i++) {
            sb.append("foo");
        }
        System.out.println("String append took "+(System.currentTimeMillis()-start)+" ms");
    }

}

The results of this test are:

String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms

So, when concatenating 100 strings, using the + incurs no significant overhead. But, if we run the same test concatenating 10000 String instead, these are the results:

String concat took 1812 ms
String append took 0 ms
String concat took 1766 ms
String append took 0 ms
String concat took 1766 ms
String append took 0 ms
String concat took 1812 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms
String concat took 1828 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms
String concat took 1782 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms

So the Java String concatenation myth is rooted in fact, but as stated on this article on Java Practices, you should use the + operator whenever you are manually concatenating a bunch of Strings, like String foo = "foo"+x+"bar"+y+"baz"+z;, because for that few of a number of Strings, the code is cleaner using the + operator and the overhead of the operator is insignificant. But, if you are pulling data from an external source and building a large String by concatenating many smaller Strings, the StringBuilder would be better to use.

Posted in Technology | Tags Java

Comments Comments Feed

1. If you decompile the .class file you'll see that you are using StringBuilder on both append() and concat() methods:

private void concat()
{
String s = "";
long l = System.currentTimeMillis();
for(int i = 0; i < iterations; i++)
s = (new StringBuilder()).append(s).append("foo").toString();

System.out.println((new StringBuilder()).append("String concat took ").
append(System.currentTimeMillis() - l).append(" ms").toString());
}

private void append()
{
StringBuilder stringbuilder = new StringBuilder();
long l = System.currentTimeMillis();
for(int i = 0; i < iterations; i++)
stringbuilder.append("foo");

System.out.println((new StringBuilder()).append("String append took ").
append(System.currentTimeMillis() - l).append(" ms").toString());
}

# Posted By Jani on Thursday, October 25 2007 at 9:00 AM

2. According to the Java Language Specification on String concatenation:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1.2, it's possible the compiler will throw out toString() calls if it can.

It's not in this case because '+=' has no choice but to force toString() to be called on each iteration. In a more likely use case, '+' would be used for string concatenation, and it would be a lot more efficient. I think you would find that StringBuilder and '+' are actually about the same since the toString() calls get thrown out by the compiler.

# Posted By Leo Przybylski on Tuesday, May 6 2008 at 12:47 AM

3. Hi,

While I was working on a Base64 encode/decoding class I basically came across a speed problem. I finally found out that the += operator on a String object is very slow.

I found myself a really fast work around though. Instead of adding one character at a time, I made sure I had a empty char[] the size the String had to be too. Instead of adding a character to the string each time I needed to I added the character to the char[].

Finally all you have to do is create a new String object using the filled char[]. So new String(arrayOfCharacters[]) for example. I know this is a response too an old post, but came across it on the internet and just really felt the urge to share my solution with you.

The same operation with += operator on a String now takes me several ms, most of the times somewhere between 0 and 300 ms depending on the size of the operation while the += operator ranged from somewhere between the 0 ms and several minutes!

Hope my response was usefull in a way. If any questions, or examples are wanted I'd be happy to share them with you as well.

Greetings,

# Posted By Arjen on Monday, July 7 2008 at 10:20 AM

4. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 6:58 AM

5. Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 6:59 AM

6. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 7:01 AM

7. http://paulbarry.com/articles/2008/09/06/ruby-on-struts

# Posted By p on Wednesday, September 1 2010 at 2:04 PM

8. Find ugg and Australian sheepskin boots, learn the history behind the Ugg boot, and when and what to wear with Cheap ugg boots, as well as cleaning and caring forAuthentic Ugg boots,Cheap ugg cardy boots,20%-40% high discount

# Posted By p on Wednesday, September 1 2010 at 2:05 PM

9. There are many people like to searching the famous brand shoes
online.
Nike Air Max
is always the best choice and you will fall in love when the first sight.As the most sought-after products,
the famous brand shoes
are not only fashionable but also practical.Nike Air Max which is one of the hottest shoes in the summer are available in a variety of styles, colors and materials.
Nike Air Max shoes
are designed for yourself.You can pick up a pair now at www.online268.com.

# Posted By online268 on Wednesday, September 1 2010 at 4:19 PM

10.
There is no doubt that when looking for Cheap nfl jerseys to buy you still want nfl shop to get something buy nfl jerseys authentic. Now that you know that there are Cheap nfl jerseys outlets out there for you to purchase and they are high quality and authentic, and I think you can buy the best one.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:14 PM

11. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:12 AM

12. louis vuitton
louis vuitton handbags
louis vuitton handbag
louis vuitton bags
louis vuitton bag
replica handbags

# Posted By ss on Thursday, September 2 2010 at 7:34 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)