summaryrefslogtreecommitdiff
path: root/benchmark/napi/function_args/index.js
blob: c8f281a3429fdedd38b2511f432e7abcd0df6f42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// show the difference between calling a V8 binding C++ function
// relative to a comparable N-API C++ function,
// in various types/numbers of arguments.
// Reports n of calls per second.
'use strict';

const common = require('../../common.js');

let v8;
let napi;

try {
  v8 = require('./build/Release/binding');
} catch (err) {
  // eslint-disable-next-line no-path-concat
  console.error(__filename + ': V8 Binding failed to load');
  process.exit(0);
}

try {
  napi = require('./build/Release/napi_binding');
} catch (err) {
  // eslint-disable-next-line no-path-concat
  console.error(__filename + ': NAPI-Binding failed to load');
  process.exit(0);
}

const argsTypes = ['String', 'Number', 'Object', 'Array', 'Typedarray',
                   '10Numbers', '100Numbers', '1000Numbers'];

const generateArgs = (argType) => {
  let args = [];

  if (argType === 'String') {
    args.push('The quick brown fox jumps over the lazy dog');
  } else if (argType === 'LongString') {
    args.push(Buffer.alloc(32768, '42').toString());
  } else if (argType === 'Number') {
    args.push(Math.floor(314158964 * Math.random()));
  } else if (argType === 'Object') {
    args.push({
      map: 'add',
      operand: 10,
      data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      reduce: 'add',
    });
  } else if (argType === 'Array') {
    const arr = [];
    for (let i = 0; i < 50; ++i) {
      arr.push(Math.random() * 10e9);
    }
    args.push(arr);
  } else if (argType === 'Typedarray') {
    const arr = new Uint32Array(1000);
    for (let i = 0; i < 1000; ++i) {
      arr[i] = Math.random() * 4294967296;
    }
    args.push(arr);
  } else if (argType === '10Numbers') {
    args.push(10);
    for (let i = 0; i < 9; ++i) {
      args = [...args, ...generateArgs('Number')];
    }
  } else if (argType === '100Numbers') {
    args.push(100);
    for (let i = 0; i < 99; ++i) {
      args = [...args, ...generateArgs('Number')];
    }
  } else if (argType === '1000Numbers') {
    args.push(1000);
    for (let i = 0; i < 999; ++i) {
      args = [...args, ...generateArgs('Number')];
    }
  }

  return args;
};

const bench = common.createBenchmark(main, {
  type: argsTypes,
  engine: ['v8', 'napi'],
  n: [1, 1e1, 1e2, 1e3, 1e4, 1e5],
});

function main({ n, engine, type }) {
  const bindings = engine === 'v8' ? v8 : napi;
  const methodName = 'callWith' + type;
  const fn = bindings[methodName];

  if (fn) {
    const args = generateArgs(type);

    bench.start();
    for (var i = 0; i < n; i++) {
      fn.apply(null, args);
    }
    bench.end(n);
  }
}