Field check vs instanceof

JavaScript performance comparison

Test case created by Sam


Imagine that you need to create objects that will behave the same way as plain JS objects but that you can distinguish later. The naive approach is to add a custom field, but this will change objects' behavior (not to mention that such a field can be accidentially overridden somewhere).

Recently I came up with a really simple idea: just create them using a custom constructor. And then you can use instanceof operator or check the constructor field to take these special objects apart from others:

var SpecialObj = (function () {
  function special () {};
  return {
    create : function () { return new special(); },
    check  : function (obj) { return obj instanceof special; },
    // or
    check2 : function (obj) { return obj.constructor === special; }

var s = SpecialObj.create();

SpecialObj.check(s); // true
SpecialObj.check({}); // false

This test is for determining the performance of the checking operation. Also see this test for the creation part.

Preparation code

Benchmark.prototype.setup = function() {
    var customCtx = function customCtx() {};
    var plain1 = { flag: true },
        plain2 = {},
        custom = new customCtx();
    var b = true;

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
b = !b || !plain1.flag || !plain2.flag;
b = !b || !(custom instanceof customCtx) || !(plain2 instanceof customCtx);
b = !b || !(custom.constructor === customCtx) || !(plain2.constructor === customCtx);

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

Compare results of other browsers


Comment form temporarily disabled.

Add a comment