querySelectorAll vs getElementsByTagName

JavaScript performance comparison

Test case created by Andrew Hedges

Preparation code

<div>
  <ul>
    <li><a href="#">item 1</a></li>
    <li><a href="#">item 2</a></li>
    <li><a href="#">item 3</a></li>
  </ul>
</div>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
querySelectorAll
var nodes = document.querySelectorAll('a')
pending…
getElementsByTagName
var nodes = document.getElementsByTagName('a')
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

5 comments

mathenk2 commented :

Wow, looks like Chrome 9.0.570 to 9.0.576 doubled its speed for getElementsByTagName. Nice! Love jsPerf!

KonP commented :

I think this test case needs to be updated - in a current scenario that I am working on, I have a very complex page (ASP.NET, SharePoint 2010 SP1, Master Page is involved) that contains cascading filters, and I must iterate through 4000-5000 divs. By using querySelectorAll I am able to get runtimes of about ~20-30ms while the getElementByTagName is executing in 200-300ms.

  • IE9 querySelectorAll: 20-30ms
  • IE9 getElementByTagName: 200-300ms
  • Chrome querySelectorAll: 5-10ms
  • Chrome getElementByTagName: 15-30ms

While the difference for Chrome can be argued, the performance in IE9 is significant.

goldy commented :

Se test est débile, querySelectorAll sert a faire des requette complexe, pas a remplacer les méthodes déjà existante, il aurait fallut comparer des requette complexe avec querySelectorAll contre l'équivalent avec les ancienne méthode avec les boucle...

Add a comment