1

I'm wondering how impactful accessing the DOM via document.getElementById or document.querySelctor is performance wise? The alternative I'm considering is accessing the elements once, let x = document.getElementById('x'); and then using this variable instead of repeated DOM queries.

I imagine using a variable would be faster, but am curious if this type of optimization is automatically handled for us by most JS engines.

Additionally, I'm considering migrating to using custom html elements with shadowRoots. Would shadow root act as a JS cache to the rendered DOM elements layer; i.e. would it make the performance gain for caching DOM elements mute? Online sources (such as [1]) explain that the shadow root is intended for encapsulation, and unlike the virtual dom, doesn't help in batching HTML updates. But does it help in accessing HTML elements?

For context, the accesses will occur for a couple dozen elements each time the user interacts with certain input fields, and they're not on a timer / loop.

[1] Is shadow DOM fast like Virtual DOM in React.js?

junvar
  • 11,151
  • 2
  • 30
  • 46
  • 1
    getElementById should just be a table lookup, so caching would not really help for it. For other methods, the main bloat will come with the complexity of your whole document. Of course, avoiding a method call is always a micro-optimization that can be made, but it will mostly help make your code cleaner. – Kaiido Oct 10 '18 at 13:39

1 Answers1

1

getElementById() should be faster than querySelector(). Also, to keep a reference to the element in a variable should be faster.

But you should see a difference only after hundreds of calls.

It will depends on the compiler performance and optimizations (that could cache some consecutive calls in some cases), and on the implementations of the HTML rendering engine...

(Native) Shadow DOM should not interfere, but the styling of the component should be faster, thanks to CSS encapsulation.

As a result, you'll need to benchmark your specific use cases to evaluate the performance gains of the different options.

Supersharp
  • 29,002
  • 9
  • 92
  • 134