Browse Source

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.

PR-URL: https://github.com/nodejs/node/pull/4414
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
process-exit-stdio-flushing
Jackson Tian 9 years ago
committed by James M Snell
parent
commit
afd821a91d
  1. 15
      benchmark/buffers/buffer_zero.js
  2. 4
      lib/buffer.js

15
benchmark/buffers/buffer_zero.js

@ -3,16 +3,21 @@
const common = require('../common.js');
const bench = common.createBenchmark(main, {
n: [1024]
n: [1024],
type: ['buffer', 'string']
});
const zero = Buffer.alloc(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++) {
Buffer.from(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
lib/buffer.js

@ -212,6 +212,10 @@ function fromString(string, encoding) {
throw new TypeError('"encoding" must be a valid string encoding');
var length = byteLength(string, encoding);
if (length === 0)
return Buffer.alloc(0);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);

Loading…
Cancel
Save