问题
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 main viable reason to "inherit" from null.
So, I wanted to check it (utilizing small, handy and cute profiler called JSLitmus):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
<script src="JSLitmus.js"></script>
<script>
JSLitmus.test('Prototypeless test', function() {
var o1 = Object.create(null);
o1.foo = "bar";
for (i = 0; i < 1000000; ++i) {
o1.foo;
};
});
JSLitmus.test('Prototypeful test', function() {
var o2 = {};
o2.foo = "bar";
for (i = 0; i < 1000000; ++i) {
o2.foo;
};
});
</script>
</head>
<body>
</body>
</html>
When executed, I've got the same (controversial) results. Does it mean that there is no performance penalty when inheriting from Object
?
回答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 () { return 42; }
});
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.
回答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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
<script src="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.
来源:https://stackoverflow.com/questions/7858621/interiting-from-null-object-does-not-seem-to-affect-performance