I want to access the parent of an element. I can access the parent by using child.parentNode but I have the parent id so i can also access it by using getElementById()
The question is: which way is better in terms of performance? And why is it better?
Advertisement
Answer
So, rather than speculating on this, I decided to leverage jsPerf to create some test cases:
The first test case uses a very simple HTML document structure:
<div id="parent"> <div id="child"> </div> </div>
It then tests child.parentNode
against querying by id
using both document.getElementById
and document.querySelector
. I ran it a few times on Chrome and a few times on Firefox:
As you can see child.parentNode
is a clear winner above both id
document
selection methods. querySelector
is easily the slowest– this is far more pronounced in Firefox than in Chrome, but clearly the slowest in both contexts.
The second test case runs the same tests, but against a slightly more complex document structure, in which our target <div>
is nested a few levels deep:
<div> <h1>Test Code</h1> <p>lorem ipsum</p> <section> <h2>Inner section</h2> <p>lorem ipsum lorem ipsum</p> <div class="example"> <h3>Example #1</h3> </div> <div class="example"> <div id="parent"> <div id="child"> </div> </div> </div> </section> </div>
As @maheer-ali points out, we would expect this to further exacerbate the performance advantage of child.parentNode
over the other methods, because we are querying the whole document, but it is worth running the experiment to verify that result.
Surprisingly, not terribly different from the results of the first test. We might expect this to change to some degree with increasingly larger document structures, but it seems unlikely we would see another front runner emerge.
I ran these tests on only two browsers, only a few times. Also, I’m running on Ubuntu, so the browser implementation and performance may differ slightly compared to Windows or MacOS versions (which will be much more popular). So it is worth testing this yourself, with several different browsers, to get a broader, more complete result set. Also, I’d invite any readers of this answer to do the same.
A word of warning, however– while the performance difference may seem drastically different, it is worth noting that the result set is shown in operations per second, where even the worst performing case of id
with querySelector
on Firefox comes in at roughly four million operations in a second. Unless you are planning selecting this parent node with extremely high frequency, you are most likely talking about a negligible performance difference. Also, keep in mind that some of these results may change– as browsers prioritize newer methods like querySelector
we might expect to see its performance improve in subsequent versions of these browsers.