Search code examples
javascriptjqueryperformancecachingdom-traversal

Is there any performance benefit from caching the document object?


I tend to cache DOM objects used in a given script but recently found myself having to call the document object within a jQuery wrapper. I was wondering if caching $(document) was even worth it considering that there's only one document object per page, which would essentially limit the lookup to one.

Although you're caching it, I'm curious as far as the overall gain if it's called multiple times. I know I'm getting a bit technical but wonder if its more effort on the browser's part to create the variable reference than explicitly writing it out to begin with.


Solution

  • Is there any performance benefit from caching the document object?

    Technically yes, but not enough of one to "mandate" caching it for performance reasons. I say "technically" because there is an object allocation and a little bit of logic involved with wrapping the document object as a jQuery object, but it's very cheap. As long as you aren't wrapping it hundreds or thousands of times, just go with whatever makes the code cleaner.