my favorite

2011/03/05

Array.push (join) v.s. String concatenation in Javascript

It's a huge misunderstanding that we always consider #1 is much faster than #2

#1

var html = [],
    i;
for (i = 0; i < 10000; i++) {
 html.push('a');
}
html.join('');
#2
var html = '',
    i;
for (i = 0; i < 10000; i++) {
 html += 'a';
}

It's true, but it's also wrong depends on which browser you test

Generally #1 is much slower than #2, except in IE and Safari

http://jsperf.com/10k-string-concat-2

Of course you can fire a new test for your own ;)

No comments:

BIO

Taipei, GuTing, Taiwan

huang47 | personal

huang47 | personal