Array.indexOf vs For loop

JavaScript performance comparison

Test case created by Thor Hanks

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var array1 = 
  [
    "value1",
    "value2",
    "value3",
    "value4",
    "value5",
    "value6",
    "value7",
    "value8",
    "value9",
    "value10",
    "value11",
    "value12",
    "value13",
    "value14",
    "value15",
    "value16",
    "value17",
    "value18",
    "value19",
    "value20"
  ];
  var array2 =
  [
    "value1",
    "value10",
    "value20"
  ];

};
</script>

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
For loop without break
for(var i = 0, len = array1.length; i < len; i++)
{
  var value = array1[i];
  var result = false;

  for(var j = 0, len = array2.length; j < len; j++)
  {
    if(value === array2[j])
    {
       result = true;
    }
  }
}
pending…
Array.indexOf()
for(var i = 0, len = array1.length; i < len; i++)
{
  var value = array1[i];
  var result = (array2.indexOf(value) !== -1);
}
pending…
For loop
for(var i = 0, len = array1.length; i < len; i++)
{
  var value = array1[i];
  var result = false;

  for(var j = 0, len = array2.length; j < len; j++)
  {
    if(value === array2[j])
    {
       result = true;
       break;
    }
  }
}
pending…

Compare results of other browsers

Revisions

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

0 Comments