1. + operator. The + operator does string concatenation as soon as one of its operands is a string. Then the other operand is converted to string. Example:
> "Say hello " + 7 + " times fast!"
’Say hello 7 times fast!’
Alternatively, you can use += where
a += b
is an abbreviation for
a = a + b
Example:
> var str = "";
> str += "Say hello ";
’Say hello ’
> str += 7;
’Say hello 7’
> str += " times fast!";
’Say hello 7 times fast!’
2. Joining an array of strings. Collect the strings to be concatenated in an array and join it afterwards.
> var arr = [];
> arr.push("Say hello ");
1
> arr.push(7);
2
> arr.push(" times fast");
3
> arr.join("")
’Say hello 7 times fast’
Which one is faster? Strings being immutable, most string operations whose results are strings produce new strings. Therefore languages such as C# or Java whose string handling is similar to JavaScript’s have special classes that help with concatenating strings. For example, C# calls this class StringBuilder. However, modern JavaScript engines optimize the + operator internally [1]. Tom Schuster mentions Ropes [2] as one possible technique for optimization. Hence there is no need for StringBuilder in JavaScript. Just use += and be done.
References:
- “Re: String concatenation” – email by Brendan Eich stating that + is faster on modern JavaScript engines.
- “Ropes: an Alternative to Strings (1995)” by Hans-J. Boehm , Russ Atkinson , Michael Plass.
3 comments:
Nah, there are more than 2. Don't forget String.concat() which can be used like "".concat.apply(null, [ "a", "b", "c" ]); for example.
Also, the array method *is* faster on IE6 and 7 in some cases, which wouldn't matter except that if you're still supporting them this is likely to be an actual bottleneck. Chrome is so fast with either that it doesn't matter that the array method is "slower".
For a definitive answer, see http://jsperf.com/string-concatenation and the revisions at the bottom of that page for lots of test cases on many browsers.
Good point. You are, however, still joining an array of strings.
You are right in that JavaScript is a widely misunderstood language. As a consequence, there is much incorrect material on the web.
BTW: A good 2ality post to get started with JavaScript is http://www.2ality.com/2011/10/javascript-overview.html
Post a Comment