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?
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.
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.
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.
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
More:
Ajaxian >> String Performance in IE: Array.join vs += continued
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With