简体   繁体   English

访问对象属性时,括号表示法是否比句点表示法慢?

[英]Is bracket notation slower than period notation for accessing Object properties?

A developer on my team mentioned that accessing an Object property via dot notation is faster than bracket notation. 我团队的开发人员提到,通过点表示法访问Object属性比使用括号表示法更快。 For example: 例如:

var sample = { name: 'First Name' }
var nameBracket = sample['name']
var namePeriod = sample.name

In this case, their belief was that the assignment of namePeriod would be faster than nameBracket . 在这种情况下,他们相信namePeriod的分配要比nameBracket的分配快。

Is this true? 这是真的? If so, why? 如果是这样,为什么? If not, why not? 如果没有,为什么不呢?

Related: How would one test this hypothesis or a similar question to determine JS function speed? 相关:如何验证这个假设或类似问题以确定JS函数速度?

When you want to try to test speeds of different approaches, it seems the defacto tool is jsperf.com. 当您想测试不同方法的速度时,事实上的工具似乎是jsperf.com。

Someone has already questioned this, and created a test for it. 有人已经对此提出质疑,并为此进行了测试。

http://jsperf.com/dot-notation-vs-square-bracket-notation http://jsperf.com/dot-notation-vs-square-bracket-notation

The results seem to be about the same. 结果似乎差不多。 What causes slowdows is when the contents of the bracket are a variable - at that point the compiler can no longer say to itself "Oh, ['foo'] is the same as .foo.. continuing on!". 造成延迟的原因是当括号中的内容是变量时–那时编译器不能再对自己说:“哦,['foo']与.foo ..继续!“相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM