Skip to content

Commit

Permalink
buffer: faster case for create buffer from empty string
Browse files Browse the repository at this point in the history
When create Buffer from empty string will touch
C++ binding also.

This patch can improve edge case ~70% faster.

PR-URL: #4414
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
JacksonTian authored and evanlucas committed Mar 30, 2016
1 parent ee83c95 commit 18db2af
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
15 changes: 10 additions & 5 deletions benchmark/buffers/buffer_zero.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@
const common = require('../common.js');

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

const zero = new Buffer(0);
const zeroBuffer = Buffer.alloc(0);
const zeroString = '';

function main(conf) {
var n = +conf.n;
bench.start();
for (let i = 0; i < n * 1024; i++) {
new Buffer(zero);
}

if (conf.type === 'buffer')
for (let i = 0; i < n * 1024; i++) Buffer.from(zeroBuffer);
else if (conf.type === 'string')
for (let i = 0; i < n * 1024; i++) Buffer.from(zeroString);

bench.end(n);
}
4 changes: 4 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ function fromString(string, encoding) {
encoding = 'utf8';

var length = byteLength(string, encoding);

if (length === 0)
return Buffer.alloc(0);

if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);

Expand Down

0 comments on commit 18db2af

Please sign in to comment.