views:

42

answers:

3

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 array 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.

+4  A: 

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.

Yacoby
+1  A: 

GMP has bit functions, like http://www.php.net/manual/en/function.gmp-clrbit.php

stereofrog
+2  A: 

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.

Gordon
Piskvor
@Piskvor yes. It's not that efficient in terms of storage. That's why I'd go with the bitmask approach Yacoby suggested (if memory is an issue). I'm just trying to give alternatives.
Gordon