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 degradation of
71cb0ef41Sopenharmony_ci * async resource propagation on the increasing number of
81cb0ef41Sopenharmony_ci * active `AsyncLocalStorage`s.
91cb0ef41Sopenharmony_ci *
101cb0ef41Sopenharmony_ci * - AsyncLocalStorage.run()
111cb0ef41Sopenharmony_ci *  - Promise
121cb0ef41Sopenharmony_ci *    - Promise
131cb0ef41Sopenharmony_ci *      ...
141cb0ef41Sopenharmony_ci *        - Promise
151cb0ef41Sopenharmony_ci */
161cb0ef41Sopenharmony_ciconst bench = common.createBenchmark(main, {
171cb0ef41Sopenharmony_ci  storageCount: [0, 1, 10, 100],
181cb0ef41Sopenharmony_ci  n: [1e5],
191cb0ef41Sopenharmony_ci});
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_cifunction runStores(stores, value, cb, idx = 0) {
221cb0ef41Sopenharmony_ci  if (idx === stores.length) {
231cb0ef41Sopenharmony_ci    cb();
241cb0ef41Sopenharmony_ci  } else {
251cb0ef41Sopenharmony_ci    stores[idx].run(value, () => {
261cb0ef41Sopenharmony_ci      runStores(stores, value, cb, idx + 1);
271cb0ef41Sopenharmony_ci    });
281cb0ef41Sopenharmony_ci  }
291cb0ef41Sopenharmony_ci}
301cb0ef41Sopenharmony_ci
311cb0ef41Sopenharmony_ciasync function runBenchmark(n) {
321cb0ef41Sopenharmony_ci  for (let i = 0; i < n; i++) {
331cb0ef41Sopenharmony_ci    // Avoid creating additional ticks.
341cb0ef41Sopenharmony_ci    await undefined;
351cb0ef41Sopenharmony_ci  }
361cb0ef41Sopenharmony_ci}
371cb0ef41Sopenharmony_ci
381cb0ef41Sopenharmony_cifunction main({ n, storageCount }) {
391cb0ef41Sopenharmony_ci  const stores = new Array(storageCount).fill(0).map(() => new AsyncLocalStorage());
401cb0ef41Sopenharmony_ci  const contextValue = {};
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_ci  runStores(stores, contextValue, () => {
431cb0ef41Sopenharmony_ci    bench.start();
441cb0ef41Sopenharmony_ci    runBenchmark(n).then(() => {
451cb0ef41Sopenharmony_ci      bench.end(n);
461cb0ef41Sopenharmony_ci    });
471cb0ef41Sopenharmony_ci  });
481cb0ef41Sopenharmony_ci}
49