• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3
4const bench = common.createBenchmark(main, {
5  encoding: ['utf8', 'base64', 'buffer'],
6  len: [2, 16, 256], // x16
7  n: [4e6]
8});
9
10// 16 chars each
11const chars = [
12  'hello brendan!!!', // 1 byte
13  'ΰαβγδεζηθικλμνξο', // 2 bytes
14  '挰挱挲挳挴挵挶挷挸挹挺挻挼挽挾挿', // 3 bytes
15  '��������������������������������', // 4 bytes
16];
17
18function main({ n, len, encoding }) {
19  let strings = [];
20  let results = [len * 16];
21  if (encoding === 'buffer') {
22    strings = [Buffer.alloc(len * 16, 'a')];
23  } else {
24    for (const string of chars) {
25      // Strings must be built differently, depending on encoding
26      const data = string.repeat(len);
27      if (encoding === 'utf8') {
28        strings.push(data);
29      } else if (encoding === 'base64') {
30        // Base64 strings will be much longer than their UTF8 counterparts
31        strings.push(Buffer.from(data, 'utf8').toString('base64'));
32      }
33    }
34
35    // Check the result to ensure it is *properly* optimized
36    results = strings.map((val) => Buffer.byteLength(val, encoding));
37  }
38
39  bench.start();
40  for (let i = 0; i < n; i++) {
41    const index = n % strings.length;
42    // Go!
43    const r = Buffer.byteLength(strings[index], encoding);
44
45    if (r !== results[index])
46      throw new Error('incorrect return value');
47  }
48  bench.end(n);
49}
50