检查数字是否在集合中的最快速方法

Quickest way to check if a number is in a set?

本文关键字:方法 数字 是否 集合 检查      更新时间:2023-09-26

在Javascript中,检查数字是否在列表中最快的方法是什么?

我知道indexOf>=,但对我来说似乎很慢。

我必须每秒执行数百万次检查,并且列表相当短(最多10个条目)

在jsperf中尝试一下,但我怀疑使用对象并将数字设置为属性会比数组搜索更快。

var theList = { 1: true, 2000: true, 253: true, -12077: true, ... };
if (theList[ someNumber ]) { // see if some number is in the list

也就是说,现在,你将无法在网络浏览器中每秒数百万次使用JavaScript做任何有用的事情,除非是在不做太多其他事情的高端机器上。

最好使用indexof()

作为一种在您的情况下不受欢迎的替代方案,使用Enumerable#include

您可以使用Enumerable#include,但我怀疑它是否比indexof()更快,比如:-

[1, 2, '3', '4', '5'].include(3);

如果你想提高理解速度,请使用array.includes:

[-1, 1, 2].includes(0)  // false
[-1, 1, 2].includes(-1) // true
[-1, 1, 2].includes(-2) // false
[-1, 1, 2].includes(2)  // true
[-1, 1, 2].includes(3)  // false