javascript object access performance

孤街醉人 提交于 2019-12-28 13:20:09

问题


In Javascript, when your getting a property of an object, is there a performance penalty to getting the whole object vs only getting a property of that object?

Also Keep in mind I'm not talking about DOM access these are pure simple Javascript objects.

For example:

Is there some kind of performance difference between the following code:

Assumed to be faster but not sure:

var length = some.object[key].length;

if(length === condition){
  // Do something that doesnt need anything inside of some.object[key]
}
else{
  var object = some.object[key];
  // Do something that requires stuff inside of some.object[key]
}

I think this would be slower but not sure if it matters.

var object = some.object[key];

if(object.length === condition){
  // Do something that doesnt need anything inside of some.object[key]
}
else{
  // Do something that requires stuff inside of some.object[key]
}

回答1:


Yes, there is a performance penalty.

The more deep is a property nested, more time will be required to perform the property lookup.

Check this free chapter of the book High Performance JavaScript, in the page 31, it talks specifically about Nested Members.

(Access time related to property depth)

See also this performance test:

  • JavaScript Data Access Test


来源:https://stackoverflow.com/questions/2936807/javascript-object-access-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!