Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it faster to access the DOM through a cached variable?

I am trying to improve my knowledge of javascript and while searching for some "best practices", someone pointed out to me that it is faster to cache the DOM document and then access it through that var instead of accessing the document object directly.

You can see the results here, on an edit I made on jsperf: http://jsperf.com/jquery-document-cached-vs-uncached/3 (edit: the title holds "jsquery" because that was the original test, my edit contains vanilla javascript, the framework makes no difference)

This really makes me curious. Basically I am introducing a new variable into the equation, how can that make things faster instead of slower?

As far as I know, "print a" should be better than "b = a; print b" (figure of speach) What's different in this case?

like image 466
BBog Avatar asked Jun 18 '12 20:06

BBog


People also ask

Which object search method is faster inside a dom?

getElementById is the fastest.

What is Dom cache?

Dom Cache is used to save rendered elements to speed POS up. To add something to Dom Cache you need to do something like this: this. cache = new screens. DomCache(); this.


2 Answers

document is not like an ordinary Javascript variable. There's no telling what odd magic is happening under the covers when accessing its attributes, especially the DOM, which may be created on demand from internal browser structures.

like image 136
Ned Batchelder Avatar answered Oct 14 '22 13:10

Ned Batchelder


I believe I found an explanation here (the emphasis on the last part is mine):

Store pointer references to in-browser objects. Use this technique to reduce DOM traversal trips by storing references to browser objects during instantiation for later usage. For example, if you are not expecting your DOM to change you should store a reference to DOM or jQuery objects you are going to use when your page is created; if you are building a DOM structure such as a dialog window, make sure you store a few handy reference to DOM objects inside it during instantiation, so you dont need to find the same DOM object over an over again when a user clicks on something or drags the dialog window.If you haven’t stored a reference to a DOM object, and you need to iterate inside a function, you can create a local variable containing a reference to that DOM object, this will considerably speed up the iteration as the local variable is stored in the most accessible part of the stack.

So, if I understand correctly, caching the DOM in a local variable makes it easier to access in the memory stack, therefore increasing the speed of execution.

like image 36
BBog Avatar answered Oct 14 '22 11:10

BBog