querySelectorAll vs getElementsByTagName

JavaScript performance comparison

Test case created by Andrew Hedges

Preparation code

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

Preparation code output

<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>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
var nodes = document.querySelectorAll('a')
var nodes = document.getElementsByTagName('a')

Compare results of other browsers


You can edit these tests or add even more tests to this page by appending /edit to the URL.


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