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 shadowRoot
s. 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.