What is a good way to represent a collection of bits?
I have a set of various on/off toggles (thousands of them) and need to store and retrieve their state. The naïve implementation would be an arra开发者_如何学Pythony of booleans, but I'm wondering if there's a better way (better in terms of access speed and/or memory requirements).
I've found this BitArray implementation, but it's limited to 32 bits, which is not enough for this case.
Another option is to store them in blocks of PHP_INT_SIZE*8
in integers and use bitwise operators to set/unset them.
I can't comment on speeds or memory consumption of this method, you may have to do some benchmarking.
You might want to have a look at the DataStructures in SPL. Depending on your UseCase, they might perform better than an array, e.g. use a FixedArray when you know the size of your collection, etc. For large datasets, this might make a difference.
Another idea would be to just concat the options into a single string of 1 and 0s. Since strings can be accessed as arrays, you could then do $options[31] to retrieve the bit at this position. All you'd need then, is a map of what position is which option.
Still, Yacoby's solution sounds the most feasible to me though.
GMP has bit functions, like http://www.php.net/manual/en/function.gmp-clrbit.php
精彩评论