Web-tech nerd stuff

Javascript performance: document.getElementById versus document.querySelector and document.querySelectorAll

I’ve been lucky enough to be working on an internal project the last few weeks which has a known set of modern browsers as the target audience. This means i’ve been able to ignore some of the older design/development issues.

I am really liking document.querySelector and document.querySelectorAll which are relatively modern (well, to me at least) as they’re so convenient to use. This did make me wonder what their performance would be like though, typically convenience is inversely proportional to performance so i thought i’d put together a quick test on;

The results vary in scale by browser but the overall trend is that document.getElementById is much faster than document.querySelector which is in turn a fair amount faster than document.querySelectorAll (which is probably a more obvious outcome).

So there you have it! Use document.getelementById wherever you can and only use document.querySelectorAll if you defintely need to locate multiple elements.


UPDATE: Just tested on Opera 12.11 (OSX) and bizarrely, it’s faster at document.querySelectorAll. Overall though Opera is a great deal slower in this test case than Chrome/Firefox. Safari 6 on OSX is immensely fast for document.getElementByID

Created: Mon, 26 Nov 2012 16:00:00 GMT
Last modified: Mon, 26 Nov 2012 16:00:00 GMT