11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common.js');
31cb0ef41Sopenharmony_ciconst { AsyncLocalStorage } = require('async_hooks');
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ci/**
61cb0ef41Sopenharmony_ci * This benchmark verifies the performance of
71cb0ef41Sopenharmony_ci * `AsyncLocalStorage.getStore()` on multiple `AsyncLocalStorage` instances
81cb0ef41Sopenharmony_ci * nested `AsyncLocalStorage.run()`s.
91cb0ef41Sopenharmony_ci *
101cb0ef41Sopenharmony_ci * - AsyncLocalStorage1.run()
111cb0ef41Sopenharmony_ci *   - AsyncLocalStorage2.run()
121cb0ef41Sopenharmony_ci *    ...
131cb0ef41Sopenharmony_ci *      - AsyncLocalStorageN.run()
141cb0ef41Sopenharmony_ci *        - AsyncLocalStorage1.getStore()
151cb0ef41Sopenharmony_ci */
161cb0ef41Sopenharmony_ciconst bench = common.createBenchmark(main, {
171cb0ef41Sopenharmony_ci  sotrageCount: [1, 10, 100],
181cb0ef41Sopenharmony_ci  n: [1e4],
191cb0ef41Sopenharmony_ci});
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_cifunction runBenchmark(store, n) {
221cb0ef41Sopenharmony_ci  for (let idx = 0; idx < n; idx++) {
231cb0ef41Sopenharmony_ci    store.getStore();
241cb0ef41Sopenharmony_ci  }
251cb0ef41Sopenharmony_ci}
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_cifunction runStores(stores, value, cb, idx = 0) {
281cb0ef41Sopenharmony_ci  if (idx === stores.length) {
291cb0ef41Sopenharmony_ci    cb();
301cb0ef41Sopenharmony_ci  } else {
311cb0ef41Sopenharmony_ci    stores[idx].run(value, () => {
321cb0ef41Sopenharmony_ci      runStores(stores, value, cb, idx + 1);
331cb0ef41Sopenharmony_ci    });
341cb0ef41Sopenharmony_ci  }
351cb0ef41Sopenharmony_ci}
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_cifunction main({ n, sotrageCount }) {
381cb0ef41Sopenharmony_ci  const stores = new Array(sotrageCount).fill(0).map(() => new AsyncLocalStorage());
391cb0ef41Sopenharmony_ci  const contextValue = {};
401cb0ef41Sopenharmony_ci
411cb0ef41Sopenharmony_ci  runStores(stores, contextValue, () => {
421cb0ef41Sopenharmony_ci    bench.start();
431cb0ef41Sopenharmony_ci    runBenchmark(stores[0], n);
441cb0ef41Sopenharmony_ci    bench.end(n);
451cb0ef41Sopenharmony_ci  });
461cb0ef41Sopenharmony_ci}
47