buffer: improve toJSON() performance
PR-URL: https://github.com/nodejs/node/pull/10895 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Michal Zasso <targos@protonmail.com> Reviewed-By: Evan Lucas <evanlucas@me.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
parent
a57e2f2138
commit
9fcd842279
18
benchmark/buffers/buffer-tojson.js
Normal file
18
benchmark/buffers/buffer-tojson.js
Normal file
@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
const common = require('../common.js');
|
||||
|
||||
const bench = common.createBenchmark(main, {
|
||||
n: [1e4],
|
||||
len: [0, 10, 256, 4 * 1024]
|
||||
});
|
||||
|
||||
function main(conf) {
|
||||
var n = +conf.n;
|
||||
var buf = Buffer.allocUnsafe(+conf.len);
|
||||
|
||||
bench.start();
|
||||
for (var i = 0; i < n; ++i)
|
||||
buf.toJSON();
|
||||
bench.end(n);
|
||||
}
|
@ -804,10 +804,14 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
|
||||
|
||||
|
||||
Buffer.prototype.toJSON = function() {
|
||||
return {
|
||||
type: 'Buffer',
|
||||
data: Array.prototype.slice.call(this, 0)
|
||||
};
|
||||
if (this.length) {
|
||||
const data = [];
|
||||
for (var i = 0; i < this.length; ++i)
|
||||
data[i] = this[i];
|
||||
return { type: 'Buffer', data };
|
||||
} else {
|
||||
return { type: 'Buffer', data: [] };
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user