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

编程入门 行业动态 更新时间:2024-10-26 18:15:38
本文介绍了jquery.inArray()与Object.hasOwnProperty()之间的性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

jsperf/array-vs-obj

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

hasOwnProperty is way way faster for the reasons stated by others.

更多推荐

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

本文发布于:2023-10-21 17:12:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1514836.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:差异   性能   inArray   jquery   hasOwnProperty

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!