diff options
author | Brendan Ashworth <brendan.ashworth@me.com> | 2015-05-15 19:24:34 -0700 |
---|---|---|
committer | Brendan Ashworth <brendan.ashworth@me.com> | 2015-05-22 15:31:03 -0700 |
commit | 9da168b71fb729635ad71e839630480e815623d0 (patch) | |
tree | 0f508d18ed0180c410dbb62b77a15dc9ab919a71 /benchmark | |
parent | 2a71f02988244b6299db8fe8ba3cc0491793acfc (diff) | |
download | node-new-9da168b71fb729635ad71e839630480e815623d0.tar.gz |
buffer: optimize Buffer.byteLength
Buffer.byteLength is important for speed because it is called whenever a
new Buffer is created from a string.
This commit optimizes Buffer.byteLength execution by:
- moving base64 length calculation into JS-land, which is now much
faster
- remove redundant code and streamline the UTF8 length calculation
It also adds a benchmark and better tests.
PR-URL: https://github.com/nodejs/io.js/pull/1713
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Diffstat (limited to 'benchmark')
-rw-r--r-- | benchmark/buffers/buffer-bytelength.js | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/benchmark/buffers/buffer-bytelength.js b/benchmark/buffers/buffer-bytelength.js new file mode 100644 index 0000000000..6a7afe6921 --- /dev/null +++ b/benchmark/buffers/buffer-bytelength.js @@ -0,0 +1,55 @@ +var common = require('../common'); + +var bench = common.createBenchmark(main, { + encoding: ['utf8', 'base64'], + len: [1, 2, 4, 16, 64, 256], // x16 + n: [5e6] +}); + +// 16 chars each +var chars = [ + 'hello brendan!!!', // 1 byte + 'ΰαβγδεζηθικλμνξο', // 2 bytes + '挰挱挲挳挴挵挶挷挸挹挺挻挼挽挾挿', // 3 bytes + '𠜎𠜱𠝹𠱓𠱸𠲖𠳏𠳕𠴕𠵼𠵿𠸎𠸏𠹷𠺝𠺢' // 4 bytes +]; + +function main(conf) { + var n = conf.n | 0; + var len = conf.len | 0; + var encoding = conf.encoding; + + var strings = []; + for (var string of chars) { + // Strings must be built differently, depending on encoding + var data = buildString(string, len); + if (encoding === 'utf8') { + strings.push(data); + } else if (encoding === 'base64') { + // Base64 strings will be much longer than their UTF8 counterparts + strings.push(new Buffer(data, 'utf8').toString('base64')); + } + } + + // Check the result to ensure it is *properly* optimized + var results = strings.map(function(val) { + return Buffer.byteLength(val, encoding); + }); + + bench.start(); + for (var i = 0; i < n; i++) { + var index = n % strings.length; + // Go! + var r = Buffer.byteLength(strings[index], encoding); + + if (r !== results[index]) + throw Error('incorrect return value'); + } + bench.end(n); +} + +function buildString(str, times) { + if (times == 1) return str; + + return str + buildString(str, times - 1); +} |