gpt4 book ai didi

javascript - JavaScript 中的 boolean 值数组

转载 作者:行者123 更新时间:2023-11-28 13:29:16 24 4
gpt4 key购买 nike

在 JavaScript 中,有没有一种方法可以更有效地做到这一点?

我需要创建一个 boolean 值数组,更改它们并随机地单独检查它们。

目标是更好的性能。也许操纵位。

现在我使用这样的东西:

var boolean = [];

var length = 100; // set a random number of values
for (var i = 0; i < length; i++) boolean[i] = false; // or true

boolean[n] = true; // change some of the values randomly
if (boolean[n]) { /* something */ } // check some of the values randomly

最佳答案

所以这分为三个部分:

  1. 创建数组

    有点违反直觉,即使标准 JavaScript 数组 aren't really arrays at all 你正在做的事情已经很好了,因为创建和填充数组的方式,现代引擎将在幕后使用真正的数组。 (有关更多信息,请参阅 my answer to this other question,包括性能测试。)因此,即使在具有 Uint8Array 等真正数组的引擎上,您所做的也很好。但请参阅下面的第 2 点。

  2. 用错误值填充它

    由于只有 100 个条目,因此如何执行此操作并不重要,除非您在紧密循环中重复创建和填充数组。如果是,那么 Uint8Array 应该获胜,因为 new Uint8Array(100) 已预先填充零,您根本不需要填写它。

  3. 访问数组的条目

    你实际上没有太多选择,你可以按照自己的方式去做。如果您按照自己的方式创建数组或者使用 Uint8Array,那么速度可能会尽可能快。

我找到http://jsperf.com有助于比较事物的方法并了解它们在现实世界的 JavaScript 引擎上的表现。例如,这里有一个测试用例,表明 Uint8Array 将在 SpiderMonkey(Firefox 引擎)上提供轻微优势,在 V8(Chrome 引擎)上大致相同,并且 < em>在 JScript(IE11 的引擎)上稍微慢一点:

标准数组:

var a, n, dead;

// Creation
a = [];

// Filling
for (n = 0; n < 100; ++n) {
a[n] = false;
}

// Accessing randomly 5,000 times
dead = 1;
for (n = 0; n < 5000; ++n) {
a[Math.floor(Math.random() * a.length)] = true;
if (a[Math.floor(Math.random() * a.length)]) {
++dead; // Just to be doing something
}
}

// Make sure engine knows we're using the result
if (dead === 0) { throw "Error in test"; }

Uint8Array:

var a, n, dead;

// Creation
a = new Uint8Array(100);

// Filling
// None!

// Accessing randomly 5,000 times
dead = 1;
for (n = 0; n < 5000; ++n) {
a[Math.floor(Math.random() * a.length)] = 1;
if (a[Math.floor(Math.random() * a.length)]) {
++dead; // Just to be doing something
}
}

// Make sure engine knows we're using the result
if (dead === 0) { throw "Error in test"; }

Chrome、Firefox 和 IE11 上的结果:

enter image description here

关于javascript - JavaScript 中的 boolean 值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26398887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com