Skip to content

Commit 7c9969b

Browse files
committed
Speed up hex formatting of binary data 5-10x
1 parent aef701d commit 7c9969b

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/util/buffer.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,19 @@ export function byteLength(input: string | Buffer | MockttpSerializedBuffer | Ui
115115
}
116116
}
117117

118+
// We sometimes do hex encoding of large buffers, so we need it to be quick! We handle that by
119+
// precalculating hex pairs, so we can do it in a simple for loop + join. This is nearly 5x
120+
// faster than just toString('hex') (before thinking about splitting & spaces) or map(toString(16)).
121+
const HEX_LOOKUP = Array.from({ length: 256 }, (_, i) =>
122+
i.toString(16).padStart(2, '0').toUpperCase()
123+
);
124+
118125
export function bufferToHex(input: Buffer) {
119-
return input.toString('hex')
120-
.replace(/(\w\w)/g, '$1 ')
121-
.trimRight();
126+
const hexPairs = new Array(input.length);
127+
for (let i = 0; i < input.length; i++) {
128+
hexPairs[i] = HEX_LOOKUP[input[i]];
129+
}
130+
return hexPairs.join(' ');
122131
}
123132

124133
export function getReadableSize(input: number | Buffer | string, siUnits = true) {

0 commit comments

Comments
 (0)