Skip to content

Commit f395172

Browse files
jasnellFishrock123
authored andcommitted
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: #7236 Reviewed-By: Fedor Indutny <[email protected]>
1 parent 8e927c7 commit f395172

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

benchmark/tls/convertprotocols.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
const tls = require('tls');
5+
6+
const bench = common.createBenchmark(main, {
7+
n: [1, 50000]
8+
});
9+
10+
function main(conf) {
11+
const n = +conf.n;
12+
13+
var i = 0;
14+
var m = {};
15+
common.v8ForceOptimization(
16+
tls.convertNPNProtocols, ['ABC', 'XYZ123', 'FOO'], m);
17+
bench.start();
18+
for (; i < n; i++) tls.convertNPNProtocols(['ABC', 'XYZ123', 'FOO'], m);
19+
bench.end(n);
20+
}

lib/tls.js

+11-9
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,19 @@ exports.getCiphers = internalUtil.cachedResult(() => {
2929
// Convert protocols array into valid OpenSSL protocols list
3030
// ("\x06spdy/2\x08http/1.1\x08http/1.0")
3131
function convertProtocols(protocols) {
32-
var buff = Buffer.allocUnsafe(protocols.reduce(function(p, c) {
33-
return p + 1 + Buffer.byteLength(c);
32+
const lens = Array(protocols.length);
33+
const buff = Buffer.allocUnsafe(protocols.reduce((p, c, i) => {
34+
var len = Buffer.byteLength(c);
35+
lens[i] = len;
36+
return p + 1 + len;
3437
}, 0));
3538

36-
protocols.reduce(function(offset, c) {
37-
var clen = Buffer.byteLength(c);
38-
buff[offset] = clen;
39-
buff.write(c, offset + 1);
40-
41-
return offset + 1 + clen;
42-
}, 0);
39+
var offset = 0;
40+
for (var i = 0, c = protocols.length; i < c; i++) {
41+
buff[offset++] = lens[i];
42+
buff.write(protocols[i], offset);
43+
offset += lens[i];
44+
}
4345

4446
return buff;
4547
}

0 commit comments

Comments
 (0)