Skip to content

Commit

Permalink
buffer: faster case for create Buffer from new Buffer(0)
Browse files Browse the repository at this point in the history
When create Buffer from a Buffer will copy data
from old to new even though length is zero.

This patch can improve edge case 4x faster.
following is benchmark results.

new: buffers/buffer_zero.js n=1024: 2463.53891
old: buffers/buffer_zero.js n=1024: 618.70801

PR-URL: #4326
Reviewed-By: Ben Noordhuis <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
JacksonTian authored and jasnell committed Dec 24, 2015
1 parent 26a8297 commit 5396baf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
18 changes: 18 additions & 0 deletions benchmark/buffers/buffer_zero.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

const common = require('../common.js');

const bench = common.createBenchmark(main, {
n: [1024]
});

const zero = new Buffer(0);

function main(conf) {
var n = +conf.n;
bench.start();
for (let i = 0; i < n * 1024; i++) {
new Buffer(zero);
}
bench.end(n);
}
4 changes: 4 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ function fromString(string, encoding) {
function fromObject(obj) {
if (obj instanceof Buffer) {
var b = allocate(obj.length);

if (b.length === 0)
return b;

obj.copy(b, 0, 0, obj.length);
return b;
}
Expand Down

0 comments on commit 5396baf

Please sign in to comment.