Is [x,y,z].join('')
really faster than x + y + z
for strings?
Under the impression that join() is faster, I started through my code to use it rather than +, then I ran into the following line in the Google Analytics code:
ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
Assuming the Google coders are among the most knowledgeable, it makes me wonder. Of course, that line is only going to run once per page load, and one could say that any speed difference is negligible. But still?
join does go through the input twice. It accomplishes this by creating a sequence from the input before the first run-through. @freakish -- FWIW, it's pretty well documented (at least on Stackoverflow) that joining a list comprehension is slightly faster than joining a generator expression.
Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.
Join is the fastest way of doing it. String. Join can look through all of the strings to work out the exact length it needs, then go again and copy all the data. This means there will be no extra copying involved.
Join. This one is interesting because uses a StringBuilder to appends each list member with a specific separator. It's a bit slower than Concat since also checks the value of the separator and appends it.
The Array .join()
method (-trick) for concatenating strings has its roots back then when websites ran on Internet Explorers like a lot. For IE6 + 7 its very true than .join()
is much faster than using the +
operator due to a really bad behavior with string operations in IE.
For other browsers the performance difference wasn't that big, so it was good advice to use .join()
(again, back then). Nowadays, most engines optimize string operations big time and unless you think any of your code runs in IE6+7 a lot, you should just use +
.
Using Firebug Console in Firefox 6.0.2 using the following code:
b = new Date().getTime(); for (var i = 0; i < 10000; i++) {a = "sfhfdshdshsdh" + "sfhsfdhsfhdsfh" + "shsfdsdgsdgsgsdfgdfsgsfdghsdfhsdh";} c = new Date().getTime(); d = c - b;
and
b = new Date().getTime(); for (var i = 0; i < 10000; i++) {a = ["sfhfdshdshsdh","sfhsfdhsfhdsfh","shsfdsdgsdgsgsdfgdfsgsfdghsdfhsdh"].join();} c = new Date().getTime(); d = c - b;
I average in the low 40s for "+" and low 50s for "join" so it seems join is slower. This is most likely because of the need to create an array for join. Also this may be different in different browsers with different interpreters.
Here is an example which I ran on google chrome.
Try some other broswers....
In chrome for me +
was always faster...
http://jsperf.com/join
http://jsperf.com/join-6
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