diff --git a/benchmark/buffers/buffer-tostring.js b/benchmark/buffers/buffer-tostring.js new file mode 100644 index 00000000000000..948052042d677b --- /dev/null +++ b/benchmark/buffers/buffer-tostring.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + arg: [true, false], + len: [0, 1, 64, 1024], + n: [1e7] +}); + +function main(conf) { + const arg = conf.arg; + const len = conf.len | 0; + const n = conf.n | 0; + const buf = Buffer(len).fill(42); + + bench.start(); + if (arg) { + for (var i = 0; i < n; i += 1) + buf.toString('utf8'); + } else { + for (var i = 0; i < n; i += 1) + buf.toString(); + } + bench.end(n); +} diff --git a/lib/buffer.js b/lib/buffer.js index 619b735fe7e74b..4625515c63c91b 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -333,8 +333,7 @@ function byteLength(string, encoding) { Buffer.byteLength = byteLength; -// toString(encoding, start=0, end=buffer.length) -Buffer.prototype.toString = function(encoding, start, end) { +function slowToString(encoding, start, end) { var loweredCase = false; start = start >>> 0; @@ -376,6 +375,16 @@ Buffer.prototype.toString = function(encoding, start, end) { loweredCase = true; } } +} + + +Buffer.prototype.toString = function() { + const length = this.length | 0; + if (length === 0) + return ''; + if (arguments.length === 0) + return this.utf8Slice(0, length); + return slowToString.apply(this, arguments); };