11cb0ef41Sopenharmony_ci// Show the difference between calling a short js function
21cb0ef41Sopenharmony_ci// relative to a comparable C++ function.
31cb0ef41Sopenharmony_ci// Reports n of calls per second.
41cb0ef41Sopenharmony_ci// Note that JS speed goes up, while cxx speed stays about the same.
51cb0ef41Sopenharmony_ci'use strict';
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciconst assert = require('assert');
81cb0ef41Sopenharmony_ciconst common = require('../../common.js');
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ci// This fails when we try to open with a different version of node,
111cb0ef41Sopenharmony_ci// which is quite common for benchmarks.  so in that case, just
121cb0ef41Sopenharmony_ci// abort quietly.
131cb0ef41Sopenharmony_ci
141cb0ef41Sopenharmony_cilet binding;
151cb0ef41Sopenharmony_citry {
161cb0ef41Sopenharmony_ci  binding = require(`./build/${common.buildType}/binding`);
171cb0ef41Sopenharmony_ci} catch {
181cb0ef41Sopenharmony_ci  console.error('misc/function_call.js Binding failed to load');
191cb0ef41Sopenharmony_ci  process.exit(0);
201cb0ef41Sopenharmony_ci}
211cb0ef41Sopenharmony_ciconst cxx = binding.hello;
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_cilet napi_binding;
241cb0ef41Sopenharmony_citry {
251cb0ef41Sopenharmony_ci  napi_binding = require(`./build/${common.buildType}/napi_binding`);
261cb0ef41Sopenharmony_ci} catch {
271cb0ef41Sopenharmony_ci  console.error('misc/function_call/index.js NAPI-Binding failed to load');
281cb0ef41Sopenharmony_ci  process.exit(0);
291cb0ef41Sopenharmony_ci}
301cb0ef41Sopenharmony_ciconst napi = napi_binding.hello;
311cb0ef41Sopenharmony_ci
321cb0ef41Sopenharmony_cilet c = 0;
331cb0ef41Sopenharmony_cifunction js() {
341cb0ef41Sopenharmony_ci  return c++;
351cb0ef41Sopenharmony_ci}
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_ciassert(js() === cxx());
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_ciconst bench = common.createBenchmark(main, {
401cb0ef41Sopenharmony_ci  type: ['js', 'cxx', 'napi'],
411cb0ef41Sopenharmony_ci  n: [1e6, 1e7, 5e7],
421cb0ef41Sopenharmony_ci});
431cb0ef41Sopenharmony_ci
441cb0ef41Sopenharmony_cifunction main({ n, type }) {
451cb0ef41Sopenharmony_ci  const fn = type === 'cxx' ? cxx : type === 'napi' ? napi : js;
461cb0ef41Sopenharmony_ci  bench.start();
471cb0ef41Sopenharmony_ci  for (let i = 0; i < n; i++) {
481cb0ef41Sopenharmony_ci    fn();
491cb0ef41Sopenharmony_ci  }
501cb0ef41Sopenharmony_ci  bench.end(n);
511cb0ef41Sopenharmony_ci}
52