Duck typing vs. instanceof

Benchmark created by Andi on


Description

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

Preparation HTML

<script>
  var array0 = [1, 2, 3],
      array1 = {
    a: 5,
    b: 7
      },
      array2 = 8,
      array3 = [
    [
     []
    ]
      ],
      toString = Object.prototype.toString;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Array - duck typing
!! (array0 && array0.concat && array0.unshift && !array0.callee); !! (array1 && array1.concat && array1.unshift && !array1.callee); !! (array2 && array2.concat && array2.unshift && !array2.callee); !! (array3 && array3.concat && array3.unshift && !array3.callee);
ready
Array - instanceof
array0 instanceof Array;
array1 instanceof Array;
array2 instanceof Array;
array3 instanceof Array;
ready
Array - cross frame compatibility
toString.call(array0) === '[object Array]';
toString.call(array1) === '[object Array]';
toString.call(array2) === '[object Array]';
toString.call(array3) === '[object Array]';

// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
ready

Revisions

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