Array of boolean values in JavaScript -



Array of boolean values in JavaScript -

in javascript, there way in more efficient way?

i need create array of boolean values, alter them , check them individually , @ random.

the goal improve performance. maybe manipulating bits.

right utilize this:

var boolean = []; var length = 100; // set random number of values (var = 0; < length; i++) boolean[i] = false; // or true boolean[n] = true; // alter of values randomly if (boolean[n]) { /* */ } // check of values randomly

so there 3 parts this:

creating array

somewhat counter-intuitively, you're doing fine though standard javascript arrays aren't arrays @ all, because way you're creating , filling in array, modern engine utilize true array behind scenes. (see my reply other question more on that, including performance tests.) on engines have true arrays uint8array, you're doing fine. see point #2 below.

filling falsey values

as there 100 entries, doesn't matter how this, unless you're creating , filling in array repeatedly in tight loop. if are, uint8array should win, because new uint8array(100) pre-filled zeroes , don't have fill in @ all.

accessing array's entries

you don't have much selection there, way you're doing it. provided create array way or utilize uint8array, that's fast it's going get.

i find http://jsperf.com helpful comparing approaches things , seeing how turn out on real-world javascript engines. instance, here's test case suggesting uint8array offer slight advantage on spidermonkey (firefox's engine), same on v8 (chrome's engine), , very slightly slower on jscript (ie11's engine):

standard array:

var a, n, dead; // creation = []; // filling (n = 0; n < 100; ++n) { a[n] = false; } // accessing randomly 5,000 times dead = 1; (n = 0; n < 5000; ++n) { a[math.floor(math.random() * a.length)] = true; if (a[math.floor(math.random() * a.length)]) { ++dead; // doing } } // create sure engine knows we're using result if (dead === 0) { throw "error in test"; }

uint8array:

var a, n, dead; // creation = new uint8array(100); // filling // none! // accessing randomly 5,000 times dead = 1; (n = 0; n < 5000; ++n) { a[math.floor(math.random() * a.length)] = 1; if (a[math.floor(math.random() * a.length)]) { ++dead; // doing } } // create sure engine knows we're using result if (dead === 0) { throw "error in test"; }

results on chrome, firefox, , ie11:

javascript boolean bit-manipulation

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -