javascript对象访问性能 [英] javascript object access performance

查看:140
本文介绍了javascript对象访问性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,当你获得一个对象的属性时,获取整个对象与仅获取该对象的属性会有性能损失吗?



请记住,我不是在谈论DOM访问,这些是纯粹简单的Javascript对象。



例如:



以下代码之间是否存在某种性能差异:



假设更快但不确定:

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

if(length === condition){
//在some.object内执行一些不需要的东西[key]
}
else {
var object = some.object [key];
//做一些需要some.object内容的东西[key]
}

我认为这会慢一点,但不确定是否重要。

  var object = some.object [key]; 

if(object.length === condition){
//在some.object内执行不需要的东西[key]
}
else {
//做一些需要some.object内容的东西[key]
}


解决方案

是的,存在性能损失。



嵌套属性越深,需要的时间越多执行属性查找。



检查此

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]
}

解决方案

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对象访问性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆