Skip to content

Commit de8f36d

Browse files
committed
buffer: faster case for create buffer from empty string
When create Buffer from empty string will touch C++ binding also. This patch can improve edge case ~70% faster.
1 parent 8baaa25 commit de8f36d

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

benchmark/buffers/buffer_zero.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,21 @@
33
const common = require('../common.js');
44

55
const bench = common.createBenchmark(main, {
6-
n: [1024]
6+
n: [1024],
7+
type: ['buffer', 'string']
78
});
89

9-
const zero = Buffer.alloc(0);
10+
const zeroBuffer = Buffer.alloc(0);
11+
const zeroString = '';
1012

1113
function main(conf) {
1214
var n = +conf.n;
1315
bench.start();
14-
for (let i = 0; i < n * 1024; i++) {
15-
Buffer.from(zero);
16-
}
16+
17+
if (conf.type === 'buffer')
18+
for (let i = 0; i < n * 1024; i++) Buffer.from(zeroBuffer);
19+
else if (conf.type === 'string')
20+
for (let i = 0; i < n * 1024; i++) Buffer.from(zeroString);
21+
1722
bench.end(n);
1823
}

lib/buffer.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,10 @@ function fromString(string, encoding) {
170170
throw new TypeError('"encoding" must be a valid string encoding');
171171

172172
var length = byteLength(string, encoding);
173+
174+
if (length === 0)
175+
return Buffer.alloc(0);
176+
173177
if (length >= (Buffer.poolSize >>> 1))
174178
return binding.createFromString(string, encoding);
175179

0 commit comments

Comments
 (0)