Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is the + operator less performant than StringBuffer.append()

On my team, we usually do string concatentation like this:

var url = // some dynamically generated URL var sb = new StringBuffer(); sb.append("<a href='").append(url).append("'>click here</a>"); 

Obviously the following is much more readable:

var url = // some dynamically generated URL var sb = "<a href='" + url + "'>click here</a>"; 

But the JS experts claim that the + operator is less performant than StringBuffer.append(). Is this really true?

like image 308
Dónal Avatar asked Sep 21 '08 21:09

Dónal


People also ask

Is StringBuffer faster than string?

The StringBuffer class is used to represent characters that can be modified. The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated.

How does StringBuffer append work?

StringBuffer append(Long l) : This method simply appends the string representation of the long argument to this StringBuffer sequence. Parameter : The method accepts a single parameter a which is the long value. Return Value: The method returns a string object after the append operation is performed.

What can I use instead of StringBuffer?

Actually for the example above you should use StringBuilder (introduced in Java 1.5) instead of StringBuffer - StringBuffer is little heavier as all its methods are synchronized.


1 Answers

Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.

Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis

join() once, concat() once, join() for, += for, concat() for

More:
Ajaxian >> String Performance in IE: Array.join vs += continued

like image 50
Eric Schoonover Avatar answered Oct 01 '22 11:10

Eric Schoonover