“中途"从空对象似乎不会影响性能 [英] "Interiting" from null object does not seem to affect performance
问题描述
我尝试更好地理解为什么应该一个(或不应该)继承自 Object (var o = Object.create(null);
).如果我的答案是正确的,性能原因似乎是从 null继承"的主要可行原因.
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.
所以,我想检查一下(使用名为 JSLitmus):
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>
执行时,我得到了相同(有争议的)结果.这是否意味着从 Object
继承时没有性能损失?
When executed, I've got the same (controversial) results. Does it mean that there is no performance penalty when inheriting from Object
?
推荐答案
我重新考虑了自己的代码并稍微修改了代码以使 foo
字段查找通过继承"链传播:
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>
通过这种方式,我在访问 o1
属性时获得了 10% 更好的结果.
In this way, I've got 10% better results when accessing the o1
property.
这篇关于“中途"从空对象似乎不会影响性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!