indexOf vs while loop

JavaScript performance comparison

Revision 2 of this test case created

Info

Compare a simple while loop to return the index of an element in an array to native indexOf. The loop counts down but that's what my code used.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    arr = [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 7, 12, 13, 14, 15, 16, 17, 18, 19, 20];
    ara = [2, 20, 2, 10, 3, 4, 18, 4, 4, 1, 7, 18, 11, 10, 15, 8, 10, 12, 9, 12];
    arc = ['dog','cat','eagle','human','mouse','flea','wasp','bee','chicken','tortoise','hare','coyote','hummingbird','ostrich','eagle','human'];
   
   
    function checkLoop(arg,needle) {
        var i = arg.length;
        while (i--) {
          if (arg[i] === needle) {
            return i;
          }
        }
        return -1;
    }
   
    function checkNative(arg,needle) {
        return arg.indexOf(needle);
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Loop Ordered
checkLoop(arr,7);
pending…
Loop Random
checkLoop(ara,7);
pending…
Loop Strings
checkLoop(arc,'hare');
pending…
Native Ordered
checkNative(arr,7);
pending…
Native Random
checkNative(ara,7);
pending…
Native String
checkNative(arc,'hare');
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. Here’s a list of current revisions for this page:

0 comments

Add a comment