isArray - duck typing vs. instanceof

JavaScript performance comparison

Revision 2 of this test case created by Andi

Info

This test is motivated by the use of duck typing in the current underscore.js implementation for _.isType() functions.

I believe we should not care about the cross frame edge case - take a look at the performance.

Preparation code

<script>
  var obj0 = [1, 2, 3],
      obj1 = {
    a: 5,
    b: 7
      },
      obj2 = [
    [
     []
    ]
      ],
      obj3 = 8,
      toString = Object.prototype.toString;
</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
duck typing
!! (obj0 && obj0.concat && obj0.unshift && !obj0.callee); !! (obj1 && obj1.concat && obj1.unshift && !obj1.callee); !! (obj2 && obj2.concat && obj2.unshift && !obj2.callee); !! (obj3 && obj3.concat && obj3.unshift && !obj3.callee);
pending…
instanceof
obj0 instanceof Array;
obj1 instanceof Array;
obj2 instanceof Array;
obj3 instanceof Array;
pending…
secure cross frame
toString.call(obj0) === '[object Array]';
toString.call(obj1) === '[object Array]';
toString.call(obj2) === '[object Array]';
toString.call(obj3) === '[object Array]';

// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
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:

1 comment

C. P. Burns commented :

This is exactly the benchmark I was looking for. The answer to this has alluded me for some time.

Add a comment