Skip to content Skip to sidebar Skip to footer

"interiting" From Null Object Does Not Seem To Affect Performance

I've tried to understand better why should one (or shouldn't) inherit from Object (var o = Object.create(null);). If I've got the answer right, performance reasons seemed to be the

Solution 1:

Yes there is no performance penalty.

Why would there be? It doesn't have the check [[Prototype]] because foo is an own property of o.

The reason you want to inherit from null is to build your own prototype chains. It's just allowing you control.

In general you would want to inherit from Object.prototype because the methods on it are useful and almost all code kind of "assumes" every thing inherits from it.

However you can just create your own chain with special logic

var newObject = Object.make(null,{
  toString: function  () { return"foobar"; },
  valueOf: function () { return42;  }
});

For some value of Object.make

And then just create instances of that

var o = Object.create(newObject);
console.log(o + 3);
console.log("foo" + o);

Live Example.

If you really want to have fine grained custom control of .valueOf and other methods then really it would make sense not to inherit from Object.prototype for debugging purposes (i.e. not accidentally using Object.prototype methods instead of your own).

Other then that I don't think there is a real use-case for it. It might be marginally faster, or take up marginally less memory.

Solution 2:

I've reconsidered my own code and slightly modified the code to make the foo field lookup to propagate through the "inheritance" chain:

<html><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8" /><title>Title</title><scriptsrc="JSLitmus.js"></script><script>var o1 = Object.create(null);
    o1.foo = "bar";

    var o2 = Object.create(o1);

    var count;

    JSLitmus.test('Prototypeless test', function() {
        while(--count) {
          o1.foo;
        };
    });

    JSLitmus.test('Prototypeful test', function() {
        while(--count) {
          o2.foo;
        };
    });

    </script></head><body></body></html>

In this way, I've got 10% better results when accessing the o1 property.

Post a Comment for ""interiting" From Null Object Does Not Seem To Affect Performance"