While fooling around with some JavaScript for a number formatting function at work, I stumbled upon this result.
It is faster to pad a string with zeros using array joins rather than the conventional for-loop. Here’s what I tested with.
var N=1000000, start, end;
// Using for-loop
start = new Date().getTime();
var j = '1';
for (var i=0; i<N; i++) {
j += '0';
}
end = new Date().getTime();
console.log(end-start);
// Using Array join
start = new Date().getTime();
var k = '1';
k += new Array(N+1).join('0');
end = new Date().getTime();
console.log(end-start);
The results show that on average, using a for-loop took 1200ms, while the Array.join() took 200ms. That’s a significant improvement! The Array.join() method takes 1/6 of the time, and this result seems consistent across different values of N.
Being a little bit cautious about the results, I wanted to make sure that Array.join() is practical in normal usage. I mean, when would you ever need to append a bijillion zeros to your number? So I modified the test a little bit, and here’s what I came up with.
var N=10000, M=10, start, end;
// Using for-loop
start = new Date().getTime();
for (var k=0; k<N; k++) {
var j = '1';
for (var i=0; i<M; i++) {
j += '0';
}
}
end = new Date().getTime();
console.log(end-start);
// Using Array join
start = new Date().getTime();
for (var k=0; k<N; k++) {
var j = '1';
j += new Array(M+1).join('0');
}
end = new Date().getTime();
console.log(end-start);
The results for the second test showed that Array.join() is still faster, with for-loop running in about 140ms and Array.join() at 85ms — for M=10.
However, it seems that the two methods are about even at M=4, and for-loop is faster for M<4, and Array.join() is faster for M>4.
So what can we take from this? I guess you’ll have to evaluate each problem on a case-by-case basis. If the average use case means a lot of zeros being padded, then Array.join() is hands-down the winner. However, if the average use case calls for less zeros to be appended, then it might be better to stick to the for-loop method. Although, at M=1, the Array.join() ran about double the time of the for-loop, which isn’t horrible.
I hope this will help some people. :)
Note: This method can apply to any cases where padding the same string x amount of times to an existing string occur.