inarraytest

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr=[0,1,2,3,4,5,6,7,8,9];
   
    function inArray(elem, array, i) {
        var len;
        if ( array ) {
            if ( array.indexOf ) {
                return array.indexOf.call( array, elem, i );
            }
            len = array.length;
            i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
            for ( ; i < len; i++ ) {
                // Skip accessing in sparse arrays
                if ( i in array && array[ i ] === elem ) {
                    return i;
                }
            }
        }
        return -1;
    }
   
};
</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
inArray last
var rtn=inArray(9,arr);
pending…
for loop last
for(var i=0,len=arr.length,rtn=-1;i<len;i++){
if(arr[i]===9){rtn=i;break;}
}
pending…
inArray middle
var rtn=inArray(4,arr);
pending…
for loop middle
for(var i=0,len=arr.length,rtn=-1;i<len;i++){
if(arr[i]===4){rtn=i;break;}
}
pending…
inArray first
var rtn=inArray(0,arr);
pending…
for loop first
for(var i=0,len=arr.length,rtn=-1;i<len;i++){
if(arr[i]===0){rtn=i;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. Here’s a list of current revisions for this page:

0 comments

Add a comment