Skip to content
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

buffer: up to 2x times faster copy of buffers #24977

Closed
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
23 changes: 23 additions & 0 deletions benchmark/buffers/buffer-copy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';
const common = require('../common.js');
const { randomBytes } = require('crypto');

const KB = 1024;

const bench = common.createBenchmark(main, {
size: [10, KB, 2 * KB, 8 * KB, 64 * KB /* , 256 * KB */],
// This option checks edge case when target.length !== source.length.
targetStart: [0, 1],
n: [1024]
});

function main({ n, size, targetStart }) {
const source = randomBytes(size);
const target = randomBytes(size);

bench.start();
for (var i = 0; i < n * 1024; i++) {
source.copy(target, targetStart);
}
bench.end(n);
}
61 changes: 57 additions & 4 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
'use strict';

const {
byteLengthUtf8,
copy: _copy,
byteLengthUtf8,
compare: _compare,
compareOffset,
createFromString,
Expand Down Expand Up @@ -401,7 +401,7 @@ function fromObject(obj) {
if (b.length === 0)
return b;

_copy(obj, b, 0, 0, obj.length);
fastcopy(obj, b, 0, 0, obj.length);
return b;
}

Expand Down Expand Up @@ -473,7 +473,7 @@ Buffer.concat = function concat(list, length) {
throw new ERR_INVALID_ARG_TYPE(
`list[${i}]`, ['Array', 'Buffer', 'Uint8Array'], list[i]);
}
_copy(buf, buffer, pos);
fastcopy(buf, buffer, pos);
pos += buf.length;
}

Expand All @@ -488,6 +488,59 @@ Buffer.concat = function concat(list, length) {
return buffer;
};

function fastcopy(source, target, targetStart = 0, sourceStart = 0, sourceEnd) {
if (!isUint8Array(source)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously we allowed any TypedArray (e.g. Uint16Array) as well as DataView as the source and target. Please also make sure to add tests for these cases.

throw new ERR_INVALID_ARG_TYPE('source', ['Buffer', 'Uint8Array'], source);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is already checked in the concat case. Therefore I recommend to move this check into Buffer.prototype.copy. The target is similar but it's created using Buffer.allocUnsafe. This function could be manipulated and therefore it would be best to have a reference to the original function and call that as e.g.: const { allocUnsafe } = Buffer;. In that case the target check can also be moved in Buffer.prototype.copy.


if (!isUint8Array(target)) {
throw new ERR_INVALID_ARG_TYPE('target', ['Buffer', 'Uint8Array'], target);
}

if (targetStart < 0)
throw new ERR_OUT_OF_RANGE('targetStart', '>= 0', targetStart);
targetStart >>>= 0;

if (sourceStart < 0)
throw new ERR_OUT_OF_RANGE('sourceStart', '>= 0', sourceStart);
sourceStart >>>= 0;

if (sourceEnd === undefined)
sourceEnd = source.byteLength;
else if (sourceEnd < 0)
throw new ERR_OUT_OF_RANGE('sourceEnd', '>= 0', sourceEnd);
else
sourceEnd >>>= 0;

if (targetStart >= target.byteLength || sourceStart >= sourceEnd)
return 0;

if (sourceStart > source.byteLength) {
throw new ERR_OUT_OF_RANGE(
'sourceStart', `<= ${source.byteLength}`, sourceStart
);
}

const targetBytesAmount = target.byteLength - targetStart;

if (sourceEnd - sourceStart > targetBytesAmount)
sourceEnd = sourceStart + targetBytesAmount;

const bytesAmount = Math.min(
sourceEnd - sourceStart,
targetBytesAmount,
source.byteLength - sourceStart
);

if (sourceStart > 0 || bytesAmount < source.byteLength) {
sourceEnd = sourceStart + bytesAmount;
return _copy(source, target, targetStart, sourceStart, sourceEnd);
}

target.set(source, targetStart);
return bytesAmount;
}

function base64ByteLength(str, bytes) {
// Handle padding
if (str.charCodeAt(bytes - 1) === 0x3D)
Expand Down Expand Up @@ -626,7 +679,7 @@ function stringSlice(buf, encoding, start, end) {

Buffer.prototype.copy =
function copy(target, targetStart, sourceStart, sourceEnd) {
return _copy(this, target, targetStart, sourceStart, sourceEnd);
return fastcopy(this, target, targetStart, sourceStart, sourceEnd);
};

// No need to verify that "buf.length <= MAX_UINT32" since it's a read-only
Expand Down
10 changes: 2 additions & 8 deletions test/parallel/test-buffer-alloc.js
Original file line number Diff line number Diff line change
Expand Up @@ -964,7 +964,8 @@ common.expectsError(
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'argument must be a buffer'
message: 'The "target" argument must be one of type Buffer or ' +
'Uint8Array. Received type undefined'
});

assert.throws(() => Buffer.from(), {
Expand Down Expand Up @@ -1009,13 +1010,6 @@ assert.strictEqual(SlowBuffer.prototype.offset, undefined);
assert.throws(() => Buffer.from(new ArrayBuffer(0), -1 >>> 0), errMsg);
}

// ParseArrayIndex() should reject values that don't fit in a 32 bits size_t.
common.expectsError(() => {
const a = Buffer.alloc(1);
const b = Buffer.alloc(1);
a.copy(b, 0, 0x100000000, 0x100000001);
}, outOfRangeError);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just because it's not obvious why the test is removed: can you elaborate why it's now obsolete?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ParseArrayIndex() isn't called without type casting to uint32 any more.

inline MUST_USE_RESULT bool ParseArrayIndex(Local<Value> arg,

// Unpooled buffer (replaces SlowBuffer)
{
const ubuf = Buffer.allocUnsafeSlow(10);
Expand Down
3 changes: 2 additions & 1 deletion test/parallel/test-buffer-copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const c = Buffer.allocUnsafe(512);
const errorProperty = {
code: 'ERR_OUT_OF_RANGE',
type: RangeError,
message: 'Index out of range'
message: 'The value of "sourceStart" is out of range. ' +
'It must be >= 0. Received -1'
};

let cntr = 0;
Expand Down