Browse Source

tls: avoid calling Buffer.byteLength multiple times

There's no reason to be calling Buffer.byteLength() twice.
Small perf improvement

Run 1:
tls/convertprotocols.js n=1     v6.2.1 = 11852,  new = 12204 ......  -2.89%
tls/convertprotocols.js n=50000 v6.2.1 = 515660, new = 570610 .....  -9.63%

Run 2:
tls/convertprotocols.js n=1     v6.2.1 = 11729,  new = 12045 ......  -2.62%
tls/convertprotocols.js n=50000 v6.2.1 = 512080, new = 637730 ..... -19.70%

PR-URL: https://github.com/nodejs/node/pull/7236
Reviewed-By: Fedor Indutny <fedor.indutny@gmail.com>
v7.x
James M Snell 8 years ago
parent
commit
f3d5efa3ee
  1. 20
      benchmark/tls/convertprotocols.js
  2. 20
      lib/tls.js

20
benchmark/tls/convertprotocols.js

@ -0,0 +1,20 @@
'use strict';
const common = require('../common.js');
const tls = require('tls');
const bench = common.createBenchmark(main, {
n: [1, 50000]
});
function main(conf) {
const n = +conf.n;
var i = 0;
var m = {};
common.v8ForceOptimization(
tls.convertNPNProtocols, ['ABC', 'XYZ123', 'FOO'], m);
bench.start();
for (; i < n; i++) tls.convertNPNProtocols(['ABC', 'XYZ123', 'FOO'], m);
bench.end(n);
}

20
lib/tls.js

@ -29,17 +29,19 @@ exports.getCiphers = internalUtil.cachedResult(() => {
// Convert protocols array into valid OpenSSL protocols list // Convert protocols array into valid OpenSSL protocols list
// ("\x06spdy/2\x08http/1.1\x08http/1.0") // ("\x06spdy/2\x08http/1.1\x08http/1.0")
function convertProtocols(protocols) { function convertProtocols(protocols) {
var buff = Buffer.allocUnsafe(protocols.reduce(function(p, c) { const lens = Array(protocols.length);
return p + 1 + Buffer.byteLength(c); const buff = Buffer.allocUnsafe(protocols.reduce((p, c, i) => {
var len = Buffer.byteLength(c);
lens[i] = len;
return p + 1 + len;
}, 0)); }, 0));
protocols.reduce(function(offset, c) { var offset = 0;
var clen = Buffer.byteLength(c); for (var i = 0, c = protocols.length; i < c; i++) {
buff[offset] = clen; buff[offset++] = lens[i];
buff.write(c, offset + 1); buff.write(protocols[i], offset);
offset += lens[i];
return offset + 1 + clen; }
}, 0);
return buff; return buff;
} }

Loading…
Cancel
Save