问题描述
我有一种情况,我可以选择将字符串键的集合作为对象来实现:
I have a situation where I can choose to implement a collection of string keys as an object:
$.each(objects, function (key, object) {
collection[key] = "doesn't matter";
});
或数组:
$.each(objects, function (key, object) {
collection.push(key);
});
我希望能够快速确定集合是否包含给定密钥。如果collection是一个对象,我可以使用:
I'd like to be able to quickly determine whether or not the collection contains a given key. If collection is an object, I can use:
if (collection.hasOwnProperty(key_to_find)) { // found it!... }
else { // didn't find it... }
如果collection是一个数组,我可以使用:
If collection is an array, I can use:
if ($.inArray(key_to_find, collection)) { // found it!... }
else { // didn't find it... }
我想像使用JavaScript的内置hasOwnProperty会比jQuery的inArray()更快,但我不完全确定。有没有人更多地了解这两种方法之间的性能差异?或者,这里有一个我不知道的更有效的替代方案吗?
I'd imagine using JavaScript's built-in hasOwnProperty would be faster than jQuery's inArray(), but I'm not entirely sure. Does anyone know more about the performance differences between these two methods? Or, is there a more efficient alternative here that I am not aware of?
推荐答案
如果我们谈的是它有多长需要检查,然后真的没有比赛:
If we're talking just how long it takes to check, then there's really no contest:
由于其他人所说的原因,hasOwnProperty的速度更快。
hasOwnProperty is way way faster for the reasons stated by others.
这篇关于jquery.inArray()与Object.hasOwnProperty()之间的性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!