Javascript:什么查找更快:array.indexOf 与对象哈希? [英] Javascript: what lookup is faster: array.indexOf vs object hash?

查看:54
本文介绍了Javascript:什么查找更快:array.indexOf 与对象哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须执行 LOT 次查找,同时解析 xmlStream 如果我需要一些标签.

I have to perform a LOT of lookups, while parsing xmlStream if i need some tag or not.

我可以使用 array.indexOf 方法(我在数组中有大约 15 个项目)或使用 object[key] 查找来完成.

I can do it with array.indexOf method (i have about ~15 items in array) or using object[key] lookup.

第二个解决方案在理论上对我来说似乎更有效,但在我的代码中看起来不太好.但如果它真的更有效率,我会保持原样.

Second solution seems more efficient in theory for me, but does not look line nice in my code. But if it is really more efficient, i would leave it as it is.

例如:

var tags = [
    'tag1',
    'tag2',
    'tag3',
    ...
];

var tags2 = {
    'tag1' : null,
    'tag2' : null,
    'tag3' : null,
}

tags.indexOf(value) // exists?
tags2[value] // exists?

推荐答案

嗯,性能取决于您的设置大小和访问模式.通常,indexOf 为 O(n),hash 为 O(1),但是,由于集合中只有大约 15 个项目,并且假设每次访问都是完全独立且等概率的,因此 hash 的优势并不存在.

Well, the performance depends on your set size and your access pattern. In general, the indexOf is O(n) and hash is O(1), however, since you only have about 15 items in the set and let's say each access is completely independent and equiprobable, the advantage of hash isn't really there.

这篇关于Javascript:什么查找更快:array.indexOf 与对象哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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