Sub topic 3
The bit array: the filter's only storage
This chapter assumes you can write basic Python, know what a hash function is at a high level, and are comfortable with bytes and the bitwise operators |, &, and <<. The previous chapters introduced the membership problem and hash functions. Here we look at the one piece of memory a Bloom filter owns: the bit array.
What the bit array is
A Bloom filter keeps no items. It does not store strings, IDs, or hashes of them. Its entire state is an array of m bits, all set to 0 when the filter is created. Inserting an item flips some of those bits to 1. Querying an item reads some of those bits.
This is why a Bloom filter is small. The memory cost depends on m, not on how long your items are. A 100-character URL and a 4-byte integer cost the same to insert.
Two properties follow from this design:
- A bit can go from 0 to 1, but nothing in the basic structure sets it back to 0.
- Bits are shared. Two different items can set the same bit, and the array does not record which item set it.
The second property is the source of false positives, which later chapters cover. For now, keep in mind that the array holds only 0s and 1s and no record of who put them there.
Packing bits into a bytearray
Python has no single-bit type, so the smallest practical unit is a byte. A bytearray of (m + 7) // 8 bytes holds m bits. The + 7 rounds up, so 10 bits need 2 bytes, not 1.
To address bit number pos:
- The byte is
pos // 8. - The bit inside that byte is
pos % 8.
class BitArray:
def __init__(self, m):
self.m = m
self.data = bytearray((m + 7) // 8)
def set(self, pos):
self.data[pos // 8] |= 1 << (pos % 8)
def get(self, pos):
return bool(self.data[pos // 8] & (1 << (pos % 8)))
def count_ones(self):
return sum(bin(byte).count("1") for byte in self.data)
bits = BitArray(20)
bits.set(3)
bits.set(3) # setting an already-set bit changes nothing
bits.set(17)
print(bits.get(3)) # True
print(bits.get(4)) # False
print(bits.count_ones()) # 2
print(len(bits.data)) # 3 bytes hold 20 bitsSetting uses OR (|=) with a mask that has a single 1. OR can only turn bits on, so setting a bit twice is harmless. Reading uses AND (&) with the same mask, which isolates that one bit.
The memory cost
The size of the array is fixed when you create the filter. At about 9.6 bits per item, which is the figure for a 1% false positive rate from the sizing formulas, one million items need about 9.6 million bits. That is roughly 1.2 MB.
| Items (n) | Bits per item | Bits (m) | Memory |
|---|---|---|---|
| 1,000 | 9.6 | about 9,600 | about 1.2 KB |
| 1,000,000 | 9.6 | about 9.6 million | about 1.2 MB |
| 1,000,000,000 | 9.6 | about 9.6 billion | about 1.2 GB |
Memory grows linearly with the item count you plan for. If you insert far more items than you sized for, the array does not grow. It just fills with 1s, and the error rate rises.
Common errors
- Forgetting to round up the byte count.
m // 8loses the last partial byte and causes anIndexErrorfor high positions. - Using a position of
mor more. Positions must fall in the range 0 tom - 1, which is why hash values are reduced with% m. - Confusing bit and byte indices. Using
posdirectly as abytearrayindex touches the wrong storage. - Using a Python list of booleans. It works, but each entry costs several bytes, so it loses the space advantage.
Exercise
A filter has m = 50 bits. How many bytes does the bytearray need, and which byte and which bit within that byte does position 37 map to?
Show answer
It needs (50 + 7) // 8 = 7 bytes. Position 37 is in byte 37 // 8 = 4, at bit 37 % 8 = 5 within that byte.
Exercise
After inserting 3 items with k = 4 positions each into a large, mostly empty array, what is the largest number of bits that can be 1, and why might the real count be lower?
Show answer
At most 12 bits, since each insertion sets at most 4. The count can be lower because positions can collide, and setting an already-set bit adds nothing.