JS: For loop vs Array.indexOf (v148)

Revision 148 of this benchmark created on


Description

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

Preparation HTML

<script>
function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}
 var ar = [];
for (var i=0;i<150000;i++){
ar.push(makeid());
}
 
</script>

Test runner

Ready to run.

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

Revisions

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