JS: For loop vs Array.indexOf (v274)

Revision 274 of this benchmark created by Paulo Barcelos on


Description

Testing speed of a standard for loop vs. Array.indexOf.

Preparation HTML

<script>
var ar = [];
for(var i = 0; i < 1000; i++){
  ar[i] = guid();
}

ar[500] = 'needle';

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
for (var i = 0; i < ar.length; i++) {
 if (ar[i] === 'needle') {
  break;
 }
}
ready
other for-loop
for (var i = 0, n = ar.length; i < n; i++) {
 if (ar[i] === 'needle') {
  break;
 }
}
ready
indexOf
var a = ar.indexOf('needle');
ready

Revisions

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