我有一个按字母顺序排列的109582个字符串数组。我的Web应用程序将对数组中是否包含给定字符串进行大量快速检查。显然我可以创建一个包含哈希表或二叉树的包装类,但是我可以使用任何本机JavaScript数据结构吗?
答案 0 :(得分:5)
不确定。制作字典对象
dict = {
string1: 1,
string2: 1,
etc
保证提供O(1)查找时间。
答案 1 :(得分:1)
有各种合适的结构和方法,请参阅下文。
大批for
循环for
循环(反向)array.includes(target)
set.has(target)
obj.hasOwnProperty(target)
target in obj
<- 慢 1.29%obj[target]
<- 最快map.has(target)
<- 慢 2.94%JSBench 测试 https://jsbench.me/3pkjlwzhbr/1
// https://jsbench.me/3pkjlwzhbr/1
// https://docs.google.com/spreadsheets/d/1WucECh5uHlKGCCGYvEKn6ORrQ_9RS6BubO208nXkozk/edit?usp=sharing
// JSBench forked from https://jsbench.me/irkhdxnoqa/2
var theArr = Array.from({ length: 10000 }, (_, el) => el)
var theSet = new Set(theArr)
var theObject = Object.assign({}, ...theArr.map(num => ({ [num]: true })))
var theMap = new Map(theArr.map(num => [num, true]))
var theTarget = 9000
// Array
function isTargetThereFor(arr, target) {
const len = arr.length
for (let i = 0; i < len; i++) {
if (arr[i] === target) {
return true
}
}
return false
}
function isTargetThereForReverse(arr, target) {
const len = arr.length
for (let i = len; i > 0; i--) {
if (arr[i] === target) {
return true
}
}
return false
}
function isTargetThereIncludes(arr, target) {
return arr.includes(target)
}
// Set
function isTargetThereSet(numberSet, target) {
return numberSet.has(target)
}
// Object
function isTargetThereHasOwnProperty(obj, target) {
return obj.hasOwnProperty(target)
}
function isTargetThereIn(obj, target) {
return target in obj
}
function isTargetThereSelectKey(obj, target) {
return obj[target]
}
// Map
function isTargetThereMap(numberMap, target) {
return numberMap.has(target)
}