Skip to content

Commit a142bb6

Browse files
authored
fix: remove while loop for setbit & getbit (#2687)
Constant time `setbit` and `getbit` in the bloom filter - was hitting performance issues when using a 30mb bloom filter
1 parent 2022036 commit a142bb6

File tree

3 files changed

+31
-12
lines changed

3 files changed

+31
-12
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/* eslint-disable no-console */
2+
const Benchmark = require('benchmark')
3+
4+
const suite = new Benchmark.Suite('bloom-filter')
5+
6+
const bits = [8, 64, 512, 4096, 32768, 262144, 2097152, 251658240]
7+
8+
bits.forEach((bit) => {
9+
suite.add(`Loop ${bit}bits`, () => {
10+
let pos = 0
11+
let shift = bit
12+
while (shift > 7) {
13+
pos++
14+
shift -= 8
15+
}
16+
})
17+
18+
suite.add(`Math Ops ${bit}bits`, () => {
19+
_ = Math.floor(bit / 8)
20+
_ = bit % 8
21+
})
22+
})
23+
24+
suite
25+
.on('cycle', (event) => console.log(String(event.target)))
26+
.run({ async: true })

packages/utils/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@
178178
"devDependencies": {
179179
"@types/netmask": "^2.0.5",
180180
"aegir": "^44.0.1",
181+
"benchmark": "^2.1.4",
181182
"delay": "^6.0.0",
182183
"it-all": "^3.0.6",
183184
"it-drain": "^3.0.7",

packages/utils/src/filters/bloom-filter.ts

+4-12
Original file line numberDiff line numberDiff line change
@@ -78,25 +78,17 @@ export class BloomFilter implements Filter {
7878
}
7979

8080
setbit (bit: number): void {
81-
let pos = 0
82-
let shift = bit
83-
while (shift > 7) {
84-
pos++
85-
shift -= 8
86-
}
81+
const pos = Math.floor(bit / 8)
82+
const shift = bit % 8
8783

8884
let bitfield = this.buffer[pos]
8985
bitfield |= (0x1 << shift)
9086
this.buffer[pos] = bitfield
9187
}
9288

9389
getbit (bit: number): boolean {
94-
let pos = 0
95-
let shift = bit
96-
while (shift > 7) {
97-
pos++
98-
shift -= 8
99-
}
90+
const pos = Math.floor(bit / 8)
91+
const shift = bit % 8
10092

10193
const bitfield = this.buffer[pos]
10294
return (bitfield & (0x1 << shift)) !== 0

0 commit comments

Comments
 (0)