Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buffer: faster case for create buffer from empty string #4414

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 = 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 changes: 4 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,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);

Expand Down