Skip to content

Commit 77331a7

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 <fedor.indutny@gmail.com>
1 parent 2c7804a commit 77331a7

2 files changed

Lines changed: 31 additions & 9 deletions

File tree

‎benchmark/tls/convertprotocols.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
3+
constcommon=require('../common.js');
4+
consttls=require('tls');
5+
6+
constbench=common.createBenchmark(main,{
7+
n: [1,50000]
8+
});
9+
10+
functionmain(conf){
11+
constn=+conf.n;
12+
13+
vari=0;
14+
varm={};
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‎

Lines changed: 11 additions & 9 deletions
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
functionconvertProtocols(protocols){
32-
varbuff=Buffer.allocUnsafe(protocols.reduce(function(p,c){
33-
returnp+1+Buffer.byteLength(c);
32+
constlens=Array(protocols.length);
33+
constbuff=Buffer.allocUnsafe(protocols.reduce((p,c,i)=>{
34+
varlen=Buffer.byteLength(c);
35+
lens[i]=len;
36+
returnp+1+len;
3437
},0));
3538

36-
protocols.reduce(function(offset,c){
37-
varclen=Buffer.byteLength(c);
38-
buff[offset]=clen;
39-
buff.write(c,offset+1);
40-
41-
returnoffset+1+clen;
42-
},0);
39+
varoffset=0;
40+
for(vari=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
returnbuff;
4547
}

0 commit comments

Comments
 (0)