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

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

You can see the results here on the edit I made on jsperf: http://jsperf.com/jquery-document-cached-vs-uncached/3 (edit: the header contains "jsquery" because it was the original test, my editing contains vanilla javascript, the frames don't matter)

I'm really curious. Basically I am introducing a new variable into an equation, how can this make things faster, not slower?

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

+6
source share
2 answers

I believe that I have found an explanation here (focus on the last part of mine):

Save links to pointers to objects in the browser. Use this method to reduce DOM workarounds by storing links to browser objects during instance creation for later use. For example, if you are not expecting the DOM to change, you should keep a reference to the DOM or jQuery objects that you intend to use when your page is created; if you are creating a DOM structure such as a dialog box, make sure that you keep a few handy references to the DOM objects inside it during the instance, so you do not need to find the same DOM object over again when the user clicks on something- either or drags dialogue window.If you do not store a reference to the DOM object, and you need to iterate within the function you can create a local variable containing a reference to the DOM object, it will significantly speed up the iteration as a local variable is stored in the most access The first part of the stack.

So, if I understand correctly, caching the DOM in a local variable simplifies access to the memory stack, which increases the speed of execution.

+2
source

document not like a regular Javascript variable. It is not known what strange magic happens under the covers when accessing its attributes, especially the DOM, which can be created on demand from the internal structures of the browser.

+2
source

Source: https://habr.com/ru/post/918402/


All Articles