Which is more efficient str += "some string" or array.push().join()

Which is more efficient str += "some string" or array.push().join()
0

#1

I know String in JavaScript is immutable which means if I concatenate strings by using +=, a new string will be created with its content being copied from the old string, the old string then gets garbage collected, but if I want to construct a string from smaller strings. which of the following 2 approaches is better.
1st approach:

var str = “”;
for (var i = 0; i < 10; i++) {
str += i;
}
return str;

2nd approach:

var array = [];
for (var i = 0; i < 10; i++) {
array.push(i);
}
return array.join("");


#2

@nhuyvan1106 Good question. In principal, your assumption is correct. In many programming languages, using string concatenation in loops is discouraged and there are dedicated classes to do that (i.e. StringBuilder in C#/Java).

Coming from those languages, I thought I should avoid += in loops, too. However, I just looked it up to be sure and here is what I’ve gathered: Modern JavaScript engines will internally optimize your first approach to behave like the second, so there is no need to do that yourself. [1]

I think one should try to write code that is easy to read for humans, even at the cost of small performance penalties.
If in doubt, you can always do a speed test yourself:

function test() {
    Math.sqrt(2);
}
var iterations = 1000000;
    time = 0, start, stop;
for (var i = 0; i < iterations; i++) {
    start = Date.now();
    test();
    stop = Date.now();
    time += stop - start;
}
console.log('Average time taken: ' + (time / iterations) +
            'ms' +  '-- total:' + time + 'ms');

Do this for both algorithms and compare the results. If you’re lazy, like me, you can also ask google instead :slight_smile:


#3

This. 100 times this. Nowadays we aren’t scraping for every byte and millisecond so there is no reason not to write code that couldn’t be easily parsed by some stranger coming in after you.