Reputation: 383
I am wondering if there is a way that allows me to store a boolean array efficiently. In my understanding, every boolean variable in JavaScript takes 1 byte or 8 bits to store. However, if I want to store a array of boolean value, 8 bits can store up to 8 boolean values actually. The rest 7 bits are wasted.
In language like C or Java, people can use bit operation like ">>", "~" to store boolean array into a int value. However, that does not work well in JavaScript since it works extremely slow in JavaScript because it needs to convert the floating number to int (See this question).
I also noticed Buffer in JavaScript which stores binary data directly. However, I cannot find a way to use it to store boolean array. I think Buffer are more focused on encoding stuff. For example, if I want to set the fifth bit of a boolean array to true, I can do data |= 1<<4
but I cannot find a way to do so in Buffer.
Any solution?
Upvotes: 1
Views: 4117
Reputation: 177
Take a look at this amazing answer: https://www.smashingmagazine.com/2011/10/optimizing-long-lists-of-yesno-values-with-javascript/
Convert the array of Boolean to 1’s and 0’s and join them as a string. For further optimization, you can represent 16 bit chunks as 1 UTF-16 character for 93% compression and store that string. It’s actually quite easy.
Upvotes: 0
Reputation: 4813
As an alternative to the accepted answer, there's also minimal-bit-array
, which ndarray-bit
is based on, both made by the creator of ndarray
itself. Very similar usage (from readme):
var x = new BitArray(100)
x.set(5, true)
console.log(x.get(4)) // Prints false
console.log(x.get(5)) // Prints true
Upvotes: 2
Reputation: 11
Is this what you mean? (Max index is 30):
function BoolArray(){
this.arr = 0;
}
BoolArray.prototype.get = function(idx){
return !!((this.arr >> idx) & 1)
}
BoolArray.prototype.set = function(idx, val){
this.arr |= (val & 1) << idx;
}
Upvotes: 1
Reputation: 29167
You can use a Bit-Vector implementation:
var bs = new BitSet;
bs.set(128, 1); // Set bit at position 128
console.log(bs.toString(16)); // Print out a hex dump with one bit set
Upvotes: 4