在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
答案 0 :(得分:5)
所以这有三个部分:
创建数组
有点违反直觉,即使标准的JavaScript数组aren't really arrays at all,您正在做的事情已经很好了,因为您创建和填充数组的方式,现代引擎将使用幕后真正的阵列。 (有关详细信息,请参阅my answer to this other question,包括性能测试。)因此,即使在具有Uint8Array
等真实数组的引擎上,您所做的也很好。但请参阅下面的第2点。
用虚假值填充
由于只有100个条目,因此除非您在紧密循环中重复创建和填充数组,否则它与您的工作方式无关。如果你是,那么Uint8Array
应该获胜,因为new Uint8Array(100)
预先填充了零,而你根本不需要填写它。
访问阵列的条目
你真的没有多少选择,你按照自己的方式去做。如果您按照自己的方式创建数组,或者使用Uint8Array
,那么可能就像它将要获得的那样快。
我发现http://jsperf.com有助于比较事物的方法,并了解它们如何在真实的JavaScript引擎上运行。例如,这是一个测试用例,表明Uint8Array
将在SpiderMonkey(Firefox的引擎)上提供轻微的优势,在V8上大致相同(Chrome&# 39; s引擎),并且在JScript(IE11&#39; s引擎)上慢慢:
标准阵列:
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上的搜索结果:
答案 1 :(得分:0)
可能就是这样
var length = 100,
item,
arr = (Array(length)).fill(1),
getRandBool = function() { return Math.random(Date()) * 10 > 6; },
getRandIdx = function() { return (Math.random(Date()) * (length + 1))|0; };
arr.forEach(function(val, idx) { arr[idx]= getRandBool(); });
arr[getRandIdx()] = getRandBool();
if(item = arr[getRandIdx()]) { console.log(item) }