diff --git a/packages/utils/benchmark/filter/bloom-filter.cjs b/packages/utils/benchmark/filter/bloom-filter.cjs new file mode 100644 index 0000000000..79ce125734 --- /dev/null +++ b/packages/utils/benchmark/filter/bloom-filter.cjs @@ -0,0 +1,26 @@ +/* eslint-disable no-console */ +const Benchmark = require('benchmark') + +const suite = new Benchmark.Suite('bloom-filter') + +const bits = [8, 64, 512, 4096, 32768, 262144, 2097152, 251658240] + +bits.forEach((bit) => { + suite.add(`Loop ${bit}bits`, () => { + let pos = 0 + let shift = bit + while (shift > 7) { + pos++ + shift -= 8 + } + }) + + suite.add(`Math Ops ${bit}bits`, () => { + _ = Math.floor(bit / 8) + _ = bit % 8 + }) +}) + +suite + .on('cycle', (event) => console.log(String(event.target))) + .run({ async: true }) diff --git a/packages/utils/package.json b/packages/utils/package.json index 9905833f8b..16308e14dc 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -178,6 +178,7 @@ "devDependencies": { "@types/netmask": "^2.0.5", "aegir": "^44.0.1", + "benchmark": "^2.1.4", "delay": "^6.0.0", "it-all": "^3.0.6", "it-drain": "^3.0.7", diff --git a/packages/utils/src/filters/bloom-filter.ts b/packages/utils/src/filters/bloom-filter.ts index a41bfd59bb..ab8f2d05a2 100644 --- a/packages/utils/src/filters/bloom-filter.ts +++ b/packages/utils/src/filters/bloom-filter.ts @@ -78,12 +78,8 @@ export class BloomFilter implements Filter { } setbit (bit: number): void { - let pos = 0 - let shift = bit - while (shift > 7) { - pos++ - shift -= 8 - } + const pos = Math.floor(bit / 8) + const shift = bit % 8 let bitfield = this.buffer[pos] bitfield |= (0x1 << shift) @@ -91,12 +87,8 @@ export class BloomFilter implements Filter { } getbit (bit: number): boolean { - let pos = 0 - let shift = bit - while (shift > 7) { - pos++ - shift -= 8 - } + const pos = Math.floor(bit / 8) + const shift = bit % 8 const bitfield = this.buffer[pos] return (bitfield & (0x1 << shift)) !== 0