Running time of document.getElementById
What is the running time of document.getElementById
? It is at most logarithmic O(log(n))
, where n is the number of elements in the DOM, because the DOM is a tree. It could also be constant O(1)
, if during parsing of the HTML document, all elements with IDs are stored in a hash. I keep on hearing browsers touting their brand spanking new javascript engine with improved DOM accesses, so I'm not even sure if the running time is the same across all browsers.
The reason I ask if because I read this on Mozilla's WebGL tutorial:
The first thing we do here is obtain 开发者_开发问答a reference to the canvas, stashing it in a global variable called canvas. Obviously if you don't need to repeatedly reference the canvas, you could avoid saving this value, and you could also save it in a local variable or member field of an object.
Maybe doing $('canvasId') is not really as cheap as a constant operation if Mozilla gave this warning. Maybe I should rewrite my code from:
$('id').writeAttribute('foo', 'bar');
console.info($('id').getWidth());
$('id').absolutize();
to:
var element = $('id');
element.writeAttribute('foo', 'bar');
console.info(element.getWidth());
element.absoltize();
Keeping a copy of a DOM node in a local variable is always better when you have to access that element multiple times. That said, I can't imagine you'll notice a difference with only three lines of code accessing that element.
精彩评论