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

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

问题描述

我必须执行 LOT 的查找,同时解析xmlStream,如果我需要一些标记。

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

我可以用array.indexOf方法(我在数组中有约15项)或使用对象[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个项目,并且假设每个访问完全独立且等概率,哈希的优势实际上并不存在。

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

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