jquery.inArray()与Object.hasOwnProperty()之间的性能差异?

Gau*_*rav 9 javascript performance jquery

我有一种情况,我可以选择将字符串键的集合实现为对象:

$.each(objects, function (key, object) {
    collection[key] = "doesn't matter";
});
Run Code Online (Sandbox Code Playgroud)

或数组:

$.each(objects, function (key, object) {
    collection.push(key);
});
Run Code Online (Sandbox Code Playgroud)

我希望能够快速确定该集合是否包含给定密钥.如果collection是一个对象,我可以使用:

if (collection.hasOwnProperty(key_to_find)) { // found it!... }
else { // didn't find it... }
Run Code Online (Sandbox Code Playgroud)

如果collection是一个数组,我可以使用:

if ($.inArray(key_to_find, collection)) { // found it!... }
else { // didn't find it... }
Run Code Online (Sandbox Code Playgroud)

我想像使用JavaScript的内置hasOwnProperty会比jQuery的inArray()更快,但我不完全确定.有没有人更多地了解这两种方法之间的性能差异?或者,这里有一个我不知道的更有效的替代方案吗?

Jam*_*gne 7

如果我们正在谈论检查需要多长时间,那么真的没有比赛:

http://jsperf.com/array-vs-obj

由于其他人所说的原因,hasOwnProperty的速度更快.