1'use strict';
2const common = require('../common.js');
3const { AsyncLocalStorage, AsyncResource } = require('async_hooks');
4
5/**
6 * This benchmark verifies the performance degradation of
7 * async resource propagation on the increasing number of
8 * active `AsyncLocalStorage`s.
9 *
10 * - AsyncLocalStorage.run() * storageCount
11 * - new AsyncResource()
12 * - new AsyncResource()
13 * ...
14 * - N new Asyncresource()
15 */
16const bench = common.createBenchmark(main, {
17  storageCount: [0, 1, 10, 100],
18  n: [1e3],
19});
20
21function runStores(stores, value, cb, idx = 0) {
22  if (idx === stores.length) {
23    cb();
24  } else {
25    stores[idx].run(value, () => {
26      runStores(stores, value, cb, idx + 1);
27    });
28  }
29}
30
31function runBenchmark(n) {
32  for (let i = 0; i < n; i++) {
33    new AsyncResource('noop');
34  }
35}
36
37function main({ n, storageCount }) {
38  const stores = new Array(storageCount).fill(0).map(() => new AsyncLocalStorage());
39  const contextValue = {};
40
41  runStores(stores, contextValue, () => {
42    bench.start();
43    runBenchmark(n);
44    bench.end(n);
45  });
46}
47