Skip to content

Commit 447dc83

Browse files
committed
perf(bits): cache bitShifts per charset
- Add bitShiftsCache and computeBitShifts helper\n- Speeds up repeated generator creation with common charsets\n- All tests passing
1 parent 34b3edf commit 447dc83

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

src/lib/bits.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ type BitShifts = readonly BitShift[]
2626
//
2727
// Only two bits are necessary to determine 100100 < 110010
2828
//
29-
const bitShifts = (chars: string): BitShifts => {
29+
const computeBitShifts = (chars: string): BitShifts => {
3030
const nBitsPerChar = bitsPerChar(chars)
3131
const baseValue = chars.length % 2 == 0 ? chars.length - 1 : chars.length
3232
const baseBitShift: BitShift = [baseValue, ceil(nBitsPerChar)]
@@ -52,6 +52,15 @@ const bitShifts = (chars: string): BitShifts => {
5252
)
5353
}
5454

55+
const bitShiftsCache = new Map<string, BitShifts>()
56+
const bitShifts = (chars: string): BitShifts => {
57+
const cached = bitShiftsCache.get(chars)
58+
if (cached) return cached
59+
const shifts = computeBitShifts(chars)
60+
bitShiftsCache.set(chars, shifts)
61+
return shifts
62+
}
63+
5564
const entropyByBytes = (skipBytes: number, entropyBuffer: ArrayBuffer, sourceBytes: EntropyByBytes) => {
5665
const entropyBytes = new Uint8Array(entropyBuffer)
5766
const bytesLen = entropyBytes.length

0 commit comments

Comments
 (0)