• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common.js');
3const StringDecoder = require('string_decoder').StringDecoder;
4
5const bench = common.createBenchmark(main, {
6  encoding: ['ascii', 'utf8', 'base64-utf8', 'base64-ascii', 'utf16le'],
7  inLen: [32, 128, 1024, 4096],
8  chunkLen: [16, 64, 256, 1024],
9  n: [25e5]
10});
11
12const UTF8_ALPHA = 'Blåbærsyltetøy';
13const ASC_ALPHA = 'Blueberry jam';
14const UTF16_BUF = Buffer.from('Blåbærsyltetøy', 'utf16le');
15
16function main({ encoding, inLen, chunkLen, n }) {
17  let alpha;
18  let buf;
19  const chunks = [];
20  let str = '';
21  const isBase64 = (encoding === 'base64-ascii' || encoding === 'base64-utf8');
22
23  if (encoding === 'ascii' || encoding === 'base64-ascii')
24    alpha = ASC_ALPHA;
25  else if (encoding === 'utf8' || encoding === 'base64-utf8')
26    alpha = UTF8_ALPHA;
27  else if (encoding === 'utf16le') {
28    buf = UTF16_BUF;
29    str = Buffer.alloc(0);
30  } else
31    throw new Error('Bad encoding');
32
33  const sd = new StringDecoder(isBase64 ? 'base64' : encoding);
34
35  for (let i = 0; i < inLen; ++i) {
36    if (i > 0 && (i % chunkLen) === 0 && !isBase64) {
37      if (alpha) {
38        chunks.push(Buffer.from(str, encoding));
39        str = '';
40      } else {
41        chunks.push(str);
42        str = Buffer.alloc(0);
43      }
44    }
45    if (alpha)
46      str += alpha[i % alpha.length];
47    else {
48      let start = i;
49      let end = i + 2;
50      if (i % 2 !== 0) {
51        ++start;
52        ++end;
53      }
54      str = Buffer.concat([
55        str,
56        buf.slice(start % buf.length, end % buf.length),
57      ]);
58    }
59  }
60
61  if (!alpha) {
62    if (str.length > 0)
63      chunks.push(str);
64  } else if (str.length > 0 && !isBase64)
65    chunks.push(Buffer.from(str, encoding));
66
67  if (isBase64) {
68    str = Buffer.from(str, 'utf8').toString('base64');
69    while (str.length > 0) {
70      const len = Math.min(chunkLen, str.length);
71      chunks.push(Buffer.from(str.substring(0, len), 'utf8'));
72      str = str.substring(len);
73    }
74  }
75
76  const nChunks = chunks.length;
77
78  bench.start();
79  for (let i = 0; i < n; ++i) {
80    for (let j = 0; j < nChunks; ++j)
81      sd.write(chunks[j]);
82  }
83  bench.end(n);
84}
85