From 3aa630d81aa9a39239559afc364b9605f988205d Mon Sep 17 00:00:00 2001 From: Nikolai Vavilov Date: Sat, 2 May 2020 20:30:44 +0300 Subject: [PATCH 1/2] buffer: improve copy() performance There is no need to create a slice when sourceEnd is out of bounds. --- benchmark/buffers/buffer-copy.js | 8 +++++--- lib/buffer.js | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/benchmark/buffers/buffer-copy.js b/benchmark/buffers/buffer-copy.js index 164f31420766d5..f1cd5edf8f7deb 100644 --- a/benchmark/buffers/buffer-copy.js +++ b/benchmark/buffers/buffer-copy.js @@ -4,16 +4,18 @@ const common = require('../common.js'); const bench = common.createBenchmark(main, { bytes: [0, 8, 128, 32 * 1024], partial: ['true', 'false'], + oob: ['true', 'false'], n: [6e6] }); -function main({ n, bytes, partial }) { +function main({ n, bytes, partial, oob }) { const source = Buffer.allocUnsafe(bytes); - const target = Buffer.allocUnsafe(bytes); + const target = Buffer.allocUnsafe(bytes * 2); const sourceStart = (partial === 'true' ? Math.floor(bytes / 2) : 0); + const sourceEnd = (oob === 'true' ? source.length + 1 : source.length); bench.start(); for (let i = 0; i < n; i++) { - source.copy(target, 0, sourceStart); + source.copy(target, 0, sourceStart, sourceEnd); } bench.end(n); } diff --git a/lib/buffer.js b/lib/buffer.js index 874227f0d44051..a818f41a26ed5b 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -257,7 +257,7 @@ function _copyActual(source, target, targetStart, sourceStart, sourceEnd) { if (nb > sourceLen) nb = sourceLen; - if (sourceStart !== 0 || sourceEnd !== source.length) + if (sourceStart !== 0 || sourceEnd < source.length) source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb); target.set(source, targetStart); From 621eb2358a54521bbd5f96ef4b9db338e367acab Mon Sep 17 00:00:00 2001 From: Nikolai Vavilov Date: Tue, 5 May 2020 13:35:34 +0300 Subject: [PATCH 2/2] remove benchmark --- benchmark/buffers/buffer-copy.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/benchmark/buffers/buffer-copy.js b/benchmark/buffers/buffer-copy.js index f1cd5edf8f7deb..164f31420766d5 100644 --- a/benchmark/buffers/buffer-copy.js +++ b/benchmark/buffers/buffer-copy.js @@ -4,18 +4,16 @@ const common = require('../common.js'); const bench = common.createBenchmark(main, { bytes: [0, 8, 128, 32 * 1024], partial: ['true', 'false'], - oob: ['true', 'false'], n: [6e6] }); -function main({ n, bytes, partial, oob }) { +function main({ n, bytes, partial }) { const source = Buffer.allocUnsafe(bytes); - const target = Buffer.allocUnsafe(bytes * 2); + const target = Buffer.allocUnsafe(bytes); const sourceStart = (partial === 'true' ? Math.floor(bytes / 2) : 0); - const sourceEnd = (oob === 'true' ? source.length + 1 : source.length); bench.start(); for (let i = 0; i < n; i++) { - source.copy(target, 0, sourceStart, sourceEnd); + source.copy(target, 0, sourceStart); } bench.end(n); }