JavaScript对象与阵列查找性能 [英] JavaScript object vs. array lookup performance

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

问题描述

在JavaScript对象中按键检索值与在单个JavaScript对象数组上进行迭代之间的性能差异是什么?



在我的情况下,我有一个包含用户信息的JavaScript对象,其中键是用户的ID,值是每个用户的信息。



我问这个的原因是因为我想使用 angular-ui-select 模块来选择用户,但是我不能使用它带有Javascript对象的模块 - 它需要一个数组。



通过切换从按键切换到迭代查找,我牺牲了多少? / p>

按键:

  var user = users [id]; 

迭代

  var user; 

for(var i = 0; i< users.length; i ++){
if(users [i] .id == id){
user =用户[I];打破;
}
}


解决方案

答案是依赖于浏览器,但是,jsperf.com上有一些性能测试。它还取决于您的数据大小。通常,当您有大量数据时,使用对象键值对会更快。对于小型数据集,数组可以更快。



数组搜索将具有不同的性能,具体取决于目标项目在数组中的位置。对象搜索将具有更一致的搜索性能,因为密钥不具有特定顺序。



同样循环遍历数组比循环throigh键更快,所以如果你计划对所有项进行操作,将它们放在一个数组中是明智的。在我的一些项目中,我同时做这两件事,因为我需要进行批量操作并从识别器快速查找。



测试:



http://jsben.ch/#/Y9jDP


What is the performance difference between retrieving the value by key in a JavaScript object vs iterating over an array of individual JavaScript objects?

In my case, I have a JavaScript object containing user information where the keys are the user's IDs and the values are each user's information.

The reason I ask this is because I would like to use the angular-ui-select module to select users, but I can't use that module with a Javascript object - it requires an array.

How much, if anything, am I sacrificing by switching from a lookup by key, to a lookup by iteration?

By key:

var user = users[id];

By iteration

var user;

for (var i = 0; i < users.length; i ++) {
  if (users[i].id == id) { 
    user = users[i]; break;
  }
}

解决方案

The answer to this is browser dependent, however, there are a few performance tests on jsperf.com on this matter. It also comes down to the size of your data. Generally it is faster to use object key value pairs when you have large amounts of data. For small datasets, arrays can be faster.

Array search will have different performance dependent on where in the array your target item exist. Object serach will have a more consistent search performance as keys doesen't have a specific order.

Also looping through arrays are faster than looping throigh keys, so if you plan on doing operations on all items, it can be wise to put them in an array. In some of my project I do both, since I need to do bulk operations and fast lookup from identificators.

A test:

http://jsben.ch/#/Y9jDP

这篇关于JavaScript对象与阵列查找性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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