match vs. getElementsByTagName vs. querySelectorAll vs. while

Benchmark created by Tom Doan on


Description

Comparing four different methods to count the number of form elements in a document.

Preparation HTML

<form id="test">
  <input type="text" />
  <input type="password" />
  <input type="checkbox" />
  <input type="radio" />
  <input type="hidden" />
  <select>
   <option>1</option>
   <option>2</option>
   <option>3</option>
  </select>
  <textarea>This is just a test...</textarea>
</form>
<p>
  Number of elements: <b id="output"></b>
</p>
<script>
  var oForm = document.getElementById('test'),
      oCount = document.getElementById('output');
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
match
var n = 0;
n += oForm.innerHTML.match(/<input/gi).length;
n += oForm.innerHTML.match(/<select/gi).length;
n += oForm.innerHTML.match(/<textarea/gi).length;
oCount.textContent = n;
ready
getElementsByTagName
var n = 0;
n += oForm.getElementsByTagName('input').length;
n += oForm.getElementsByTagName('select').length;
n += oForm.getElementsByTagName('textarea').length;
oCount.textContent = n;
ready
querySelectorAll
var n = oForm.querySelectorAll('input, select, textarea').length;
oCount.textContent = n;
ready
while
var n = 0,
    o = oForm.firstChild;
while (o) {
 if (o.nodeName == 'INPUT' || o.nodeName == 'SELECT' || o.nodeName == 'TEXTAREA') n++;
 o = o.nextSibling;
}
oCount.textContent = n;
ready

Revisions

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

  • Revision 1: published by Tom Doan on