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(";");
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(";");
Share
Improve this question
edited Jul 15, 2013 at 12:21
holographic-principle
19.7k10 gold badges47 silver badges62 bronze badges
asked Dec 13, 2012 at 13:55
Christophe DeboveChristophe Debove
6,29621 gold badges75 silver badges125 bronze badges
13
- 3 Are you planning to do this 10,000 times in a row? If you don't, it likely won't matter. – Pekka Commented Dec 13, 2012 at 13:55
- 6 yes I do for 100000times – Christophe Debove Commented Dec 13, 2012 at 13:59
- 2 @MinkoGechev Noticeable to who? JS is client side. Even if the combined performance loss of every user were huge, neither the server nor an individual user see any difference. – JJJ Commented Dec 13, 2012 at 14:07
- 3 @MinkoGechev nothing here suggests that we're talking about node.js. – JJJ Commented Dec 13, 2012 at 14:09
- 1 @Juhana and also nothing suggests that we don't...The question was about JavaScript. – Minko Gechev Commented Dec 13, 2012 at 14:10
3 Answers
Reset to default 14It 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.
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).
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