diff --git a/benchmark/buffers/buffer-equals.js b/benchmark/buffers/buffer-equals.js new file mode 100644 index 00000000000000..99d2472bd3a088 --- /dev/null +++ b/benchmark/buffers/buffer-equals.js @@ -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); +} diff --git a/lib/buffer.js b/lib/buffer.js index 7b656496e53efb..7f33bcab5e164a 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -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; diff --git a/test/benchmark/test-benchmark-buffer.js b/test/benchmark/test-benchmark-buffer.js index 1dde9cf43a5e37..6ce0e542a93474 100644 --- a/test/benchmark/test-benchmark-buffer.js +++ b/test/benchmark/test-benchmark-buffer.js @@ -12,6 +12,7 @@ runBenchmark('buffers', 'bytes=0', 'byteLength=1', 'charsPerLine=6', + 'difflen=false', 'encoding=utf8', 'endian=BE', 'len=256',