Reputation: 6296
For this code I want to know in javascript what is the best approach?
var output = foo +";"+bar;
or
var output = new Array(foo,bar).join(";");
Upvotes: 9
Views: 10928
Reputation: 25682
There are many test cases in http://jsperf.com/ (for example http://jsperf.com/joint-vs-concat). There you can check which is slower. In my experience depends on the user's browser (to be more exact - JS engine).
Upvotes: 1
Reputation: 4591
According to me String concatenation is faster then array joins . saw these test cases
http://jsperf.com/array-join-vs-string-connect
http://jsperf.com/join-concat/2
Upvotes: 0
Reputation: 382102
It doesn't really matter.
There were blogs promoting the first one or the second one, depending on their benchmarks.
But the truth is that javascript engines are heavily optimized and changing, so you won't find a big reproducible and cross-browser difference.
Choose the most readable. Generally it's the first one.
If you really do a loop with 10000 times this push, benchmark it on your customer browsers in your real code, and choose the best but only if there is a significative difference. Don't forget that javascript is fast.
Upvotes: 14