JS: For loop vs Array.indexOf (v248)

Revision 248 of this benchmark created on


Description

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

Preparation HTML

<script>
  var ar = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9];
</script>

Setup

Array.prototype.myio = function(search) {
      for (var i = 0, _len=this.length; i < _len; i++) {
        if (this[i] == search) {return i}
      }
      return -1
    }
    Array.prototype.myio3 = function(search) {
      for (var i = 0, _len=this.length; i < _len; i++) {
        if (this[i] === search) {return i}
      }
      return -1
    }
    
    Array.prototype.myio4 = function(search) {
      search = search.toString()
      return this.indexOf(search);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
For loop == this
ar.myio(40)
ready
For loop == ar
ar.myio3(40)
ready
indexOf
ar.myio4(40)
ready

Revisions

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