11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common.js');
31cb0ef41Sopenharmony_ciconst { AsyncLocalStorage, AsyncResource } = require('async_hooks');
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ci/**
61cb0ef41Sopenharmony_ci * This benchmark verifies the performance of
71cb0ef41Sopenharmony_ci * `AsyncLocalStorage.getStore()` on propagation through async
81cb0ef41Sopenharmony_ci * resource scopes.
91cb0ef41Sopenharmony_ci *
101cb0ef41Sopenharmony_ci * - AsyncLocalStorage.run()
111cb0ef41Sopenharmony_ci *  - AsyncResource.runInAsyncScope
121cb0ef41Sopenharmony_ci *    - AsyncResource.runInAsyncScope
131cb0ef41Sopenharmony_ci *      ...
141cb0ef41Sopenharmony_ci *        - AsyncResource.runInAsyncScope
151cb0ef41Sopenharmony_ci *          - AsyncLocalStorage.getStore()
161cb0ef41Sopenharmony_ci */
171cb0ef41Sopenharmony_ciconst bench = common.createBenchmark(main, {
181cb0ef41Sopenharmony_ci  resourceCount: [10, 100, 1000],
191cb0ef41Sopenharmony_ci  n: [1e4],
201cb0ef41Sopenharmony_ci});
211cb0ef41Sopenharmony_ci
221cb0ef41Sopenharmony_cifunction runBenchmark(store, n) {
231cb0ef41Sopenharmony_ci  for (let i = 0; i < n; i++) {
241cb0ef41Sopenharmony_ci    store.getStore();
251cb0ef41Sopenharmony_ci  }
261cb0ef41Sopenharmony_ci}
271cb0ef41Sopenharmony_ci
281cb0ef41Sopenharmony_cifunction runInAsyncScopes(resourceCount, cb, i = 0) {
291cb0ef41Sopenharmony_ci  if (i === resourceCount) {
301cb0ef41Sopenharmony_ci    cb();
311cb0ef41Sopenharmony_ci  } else {
321cb0ef41Sopenharmony_ci    const resource = new AsyncResource('noop');
331cb0ef41Sopenharmony_ci    resource.runInAsyncScope(() => {
341cb0ef41Sopenharmony_ci      runInAsyncScopes(resourceCount, cb, i + 1);
351cb0ef41Sopenharmony_ci    });
361cb0ef41Sopenharmony_ci  }
371cb0ef41Sopenharmony_ci}
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_cifunction main({ n, resourceCount }) {
401cb0ef41Sopenharmony_ci  const store = new AsyncLocalStorage();
411cb0ef41Sopenharmony_ci  runInAsyncScopes(resourceCount, () => {
421cb0ef41Sopenharmony_ci    bench.start();
431cb0ef41Sopenharmony_ci    runBenchmark(store, n);
441cb0ef41Sopenharmony_ci    bench.end(n);
451cb0ef41Sopenharmony_ci  });
461cb0ef41Sopenharmony_ci}
47