Skip to content

Commit 5396baf

Browse files
JacksonTianjasnell
authored andcommitted
buffer: faster case for create Buffer from new Buffer(0)
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]>
1 parent 26a8297 commit 5396baf

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

benchmark/buffers/buffer_zero.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
const bench = common.createBenchmark(main, {
6+
n: [1024]
7+
});
8+
9+
const zero = new Buffer(0);
10+
11+
function main(conf) {
12+
var n = +conf.n;
13+
bench.start();
14+
for (let i = 0; i < n * 1024; i++) {
15+
new Buffer(zero);
16+
}
17+
bench.end(n);
18+
}

lib/buffer.js

+4
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,10 @@ function fromString(string, encoding) {
121121
function fromObject(obj) {
122122
if (obj instanceof Buffer) {
123123
var b = allocate(obj.length);
124+
125+
if (b.length === 0)
126+
return b;
127+
124128
obj.copy(b, 0, 0, obj.length);
125129
return b;
126130
}

0 commit comments

Comments
 (0)