[Javascript] Efficiency of innerHTML over DOM tree manipulation

Nick Fitzsimons nick at nickfitz.co.uk
Wed Jun 28 12:20:54 CDT 2006


Matt Barton wrote:
> I'm pretty certain I know what the problem is - it's generating some 
> (deliberately) extremely complicated pages, and a fair amount of page 
> generation, after loading the page, in javascript.  I'm after finding 
> out the best way to make that as efficient as possible.
> 

As others have mentioned, look closely at how you're concatenating 
strings. You probably have code similar to the following:

function concatenateStrings(values) {
	var options = "";
	for (var i = 0; i < values.length; i++) {
		options += '<option value="' + values[i] + '">' + values[i] + '</option>';
	}
	return options;
}

Changing that for:

function joinArray(values) {
	var options = [];
	for (var i = 0; i < values.length; i++) {
		options.push('<option value="');
		options.push(values[i]);
		options.push('">');
		options.push(values[i]);
		options.push('</option>');
	}
	return options.join("");
}

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.

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/





More information about the Javascript mailing list