我如何才能在 Javascript 中存储大量唯一条目?

How might I go about storing a massive number of unique entries in Javascript?

我正在尝试一个项目,该项目要求我记录用户访问的每个唯一 URL,目标是找到一种存储每个数组以保持其唯一性的方法。

有没有有效的方法来做到这一点?显然,这在理论上可能很大,如果它是一个数组,则可能有数万个条目——我该如何存储它们?

(我确实意识到这是含糊不清的,但即使您的回答是“否”,这也不太可能或聪明有用:))

...possibly tens of thousands of entries if it was an array which would not do...

数组可以包含数万甚至数十万个元素。

但为了唯一性,您需要 Set 而不是数组,因为与数组的线性查找时间相比,它提供 sub-linear 查找时间,并且唯一值集的语义更好。 .

下面是构建一百万个唯一 otherwise-random 号码的示例:

const set = new Set();
console.time("Time to build the set");
while (set.size < 1_000_000) {
    set.add(Math.random()); // Won't add duplicate elements
}
console.timeEnd("Time to build the set");
console.log(`The set contains ${set.size.toLocaleString()} unique otherwise-random numbers`);

对我来说,运行大约需要 200 毫秒。而在 分钟 .

之后,我放弃了使用数组的等效方法