JavaScript中的布尔值数组

Car*_*Gil 0 javascript boolean bit-manipulation

在JavaScript中,有没有办法以更有效的方式执行此操作?

我需要创建一个布尔值数组,更改它们并随机单独检查它们.

目标是提高性能.也许操纵位.

现在我使用这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

所以这有三个部分:

  1. 创建数组

    有点违反直觉,即使标准的JavaScript数组根本不是真正的数组,你所做的事情已经很好,因为你创建和填充数组的方式,现代引擎将使用真正的数组场景.(有关更多信息,请参阅我对这个问题的回答,包括性能测试.)所以即使在具有真正数组的引擎上Uint8Array,你所做的也很好.但请参阅下面的第2点.

  2. 填充虚假值

    因为只有100个条目,所以除非你在紧密循环中重复创建和填充数组,否则无论你怎么做都没关系.如果你是,那么一个Uint8Array应该赢,因为new Uint8Array(100)预先填充零,你根本不需要填写它.

  3. 访问阵列的条目

    那里你没有太多选择,你按照自己的方式去做.如果你按照自己的方式创建数组,或者你使用a Uint8Array,那可能和它一样快.

我发现http://jsperf.com对于比较事物的方法以及了解它们如何在真实世界的JavaScript引擎上发挥作用是有帮助的.例如,这是一个测试案例,表明一个Uint8Array将在SpiderMonkey(Firefox的引擎)上提供一点点优势,在V8(Chrome的引擎)上大致相同,在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"; }
Run Code Online (Sandbox Code Playgroud)

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"; }
Run Code Online (Sandbox Code Playgroud)

Chrome,Firefox和IE11上的搜索结果:

在此输入图像描述