javascript散列/数组混合性能

javascript hash/array hybrid performance

本文关键字:混合性 性能 混合 数组 散列 javascript      更新时间:2023-09-26

对于我的应用程序,我需要一个可以按键进行快速迭代和快速查找的集合。

示例数据

var data = [
   { myId: 4324, val: "foo"},
   { myId: 6280, val: "bar"},
   { myId: 7569, val: "baz"},
   ... x 100,000
];

密钥包含在我要存储的对象中。我一起黑了Harray(哈希数组)https://gist.github.com/3451147.

以下是的使用方法

// initialize with the key property name
var coll = new Harray("myId");
// populate with data
data.forEach(function(item){ coll.add(item); });
// key lookup
coll.h[4324] // => { myId: 4324, val: "foo"}
// array functionality
coll[1] // => { myId: 6280, val: "bar"}
coll.map(function(item){ return item.val; }); // => ["foo", "bar", "baz"]
coll.length // => 3
// remove value
coll.remove(coll[0]); // delete => { myId: 4324, val: "foo"}
// by key
coll.removeKey(7569) // delete => { myId: 7569, val: "baz"}
// by index
coll.removeAt(0); // delete => { myId: 6280, val: "bar"}

移除速度似乎是我能看到的唯一折衷。存储的对象在hObjectArray之间共享,所以我不存储任何内容的2个副本。

问题

  1. 我应该坚持使用for in来遍历对象属性吗
  2. 是否保留对象的键数组,而不是对象本身
  3. 其他选择

注意:浏览器兼容性不是一个因素。这是铬专用的。

为了知道特定集合是否有用,您必须:

  • 首先验证是否存在性能问题。如果它足够快,不要担心。要检查这一点,假设整个页面都很慢,请使用类似Chrome探查器的探查器来检查问题是否在您当前使用的集合中

  • 然后检查你正在构建的备用集合是否真的更快。要做到这一点,一个常见的解决方案是使用像http://jsperf.com/(或者简单地通过构建自己的定时测试)。

只有在那之后,你才应该努力确保你的解决方案是API完整的,完全没有bug,(使用测试单元)等等

做我第一次提到的两项检查可能会防止无用的工作,因为V8引擎中的标准对象速度惊人且智能。