Skip to content

Commit 35bca31

Browse files
mscdexBridgeAR
authored andcommitted
buffer: improve equals() performance
PR-URL: #29199 Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Yongsheng Zhang <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]> Reviewed-By: Rich Trott <[email protected]>
1 parent a123a20 commit 35bca31

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

benchmark/buffers/buffer-equals.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'use strict';
2+
const common = require('../common.js');
3+
4+
const bench = common.createBenchmark(main, {
5+
size: [0, 512, 16386],
6+
difflen: ['true', 'false'],
7+
n: [1e6]
8+
});
9+
10+
function main({ n, size, difflen }) {
11+
const b0 = Buffer.alloc(size, 'a');
12+
const b1 = Buffer.alloc(size + (difflen === 'true' ? 1 : 0), 'a');
13+
14+
if (b1.length > 0)
15+
b1[b1.length - 1] = 'b'.charCodeAt(0);
16+
17+
bench.start();
18+
for (let i = 0; i < n; i++) {
19+
b0.equals(b1);
20+
}
21+
bench.end(n);
22+
}

lib/buffer.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -716,10 +716,14 @@ Buffer.prototype.equals = function equals(otherBuffer) {
716716
throw new ERR_INVALID_ARG_TYPE(
717717
'otherBuffer', ['Buffer', 'Uint8Array'], otherBuffer);
718718
}
719+
719720
if (this === otherBuffer)
720721
return true;
721722

722-
return _compare(this, otherBuffer) === 0;
723+
if (this.byteLength !== otherBuffer.byteLength)
724+
return false;
725+
726+
return this.byteLength === 0 || _compare(this, otherBuffer) === 0;
723727
};
724728

725729
let INSPECT_MAX_BYTES = 50;

test/benchmark/test-benchmark-buffer.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ runBenchmark('buffers',
1212
'bytes=0',
1313
'byteLength=1',
1414
'charsPerLine=6',
15+
'difflen=false',
1516
'encoding=utf8',
1617
'endian=BE',
1718
'len=256',

0 commit comments

Comments
 (0)