Skip to content

buffer: improve equals() performance #29199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions benchmark/buffers/buffer-equals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';
const common = require('../common.js');

const bench = common.createBenchmark(main, {
size: [0, 512, 16386],
difflen: ['true', 'false'],
n: [1e6]
});

function main({ n, size, difflen }) {
const b0 = Buffer.alloc(size, 'a');
const b1 = Buffer.alloc(size + (difflen === 'true' ? 1 : 0), 'a');

if (b1.length > 0)
b1[b1.length - 1] = 'b'.charCodeAt(0);

bench.start();
for (let i = 0; i < n; i++) {
b0.equals(b1);
}
bench.end(n);
}
6 changes: 5 additions & 1 deletion lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -716,10 +716,14 @@ Buffer.prototype.equals = function equals(otherBuffer) {
throw new ERR_INVALID_ARG_TYPE(
'otherBuffer', ['Buffer', 'Uint8Array'], otherBuffer);
}

if (this === otherBuffer)
return true;

return _compare(this, otherBuffer) === 0;
if (this.byteLength !== otherBuffer.byteLength)
return false;

return this.byteLength === 0 || _compare(this, otherBuffer) === 0;
};

let INSPECT_MAX_BYTES = 50;
Expand Down
1 change: 1 addition & 0 deletions test/benchmark/test-benchmark-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ runBenchmark('buffers',
'bytes=0',
'byteLength=1',
'charsPerLine=6',
'difflen=false',
'encoding=utf8',
'endian=BE',
'len=256',
Expand Down