[Javascript] Efficiency of innerHTML over DOM tree manipulation

Henrik Danielsson h.danielsson at gmail.com
Fri Jun 30 14:09:18 CDT 2006


2006/6/28, Nick Fitzsimons <nick at nickfitz.co.uk>:
>
> is much faster on Internet Explorer for Windows. I've put up a test page
> at
> < http://www.nickfitz.co.uk/tests/javascript/strings.html>
> where you can try the two methods side-by-side for 1000, 10000 and 20000
> values; 20000 takes a looong time for the first method, ~68000ms on my
> machine versus ~1700ms for the second method.
>
> Interestingly, Firefox appears to be much more heavily optimised for
> string manipulation: on the same machine, the equivalent timings are
> both ~1100ms.




Interesting indeed, I get 20000 tests: 32719ms for strings and 891ms for
arrays in IE.
FF gives me  640ms with strings vs 766ms with arrays, which is quite
imressed with.
But most impressive is the 1000 loop tests in FF. Strings always take 0ms,
arrays either 0ms or 15ms, I wonder how they pull that off...

I also tried som other variants:

Test 1
options.push('<option value="',values[i],'">',values[i],'</option>');
IE 750ms, FF 703ms.

Test 2
options.push('<option value="'+values[i]+'">'+values[i]+'</option>');
IE 812ms, FF 516ms.

Test 3
options.push(['<option
value="'+values[i]+'">'+values[i]+'</option>'].join());
IE 1078ms, FF 687ms.

Test 4
var options = [values.length]; // Both browser are a few ms faster when the
length is predefined.
for (var i = 0; i < values.length; i++) {
 options[i]=['<option value="'+values[i]+'">'+values[i]+'</option>'].join();
}
return options.join("");
IE 1250ms, FF 703ms.

Test 5
Same as Test 4 but:
options[i]=['<option value="'+values[i]+'">'+values[i]+'</option>'].join();
IE 1047ms, FF 687-703ms.

Test 6
for (var i = 0; i < values.length; i++) {
 values[i]=['<option value="'+values[i]+'">'+values[i]+'</option>'].join();
}
return values.join("");
IE 766ms,FF 672ms.

We have a winner! I vote for Test 1 since Test 6 uses an extra join
operation, which doesn't feel right...
If one stores values.length in a variable instead of checking it directly,
FF goes down to about 610ms.
It however doesn't seem to make a difference in IE. Things like looping
backwards and while-looping didn't seem to make a difference at all in any
of them.

This will change how I deal with strings for sure!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.evolt.org/pipermail/javascript/attachments/20060630/520c5255/attachment.htm>


More information about the Javascript mailing list