• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common.js');
3const { AsyncLocalStorage, AsyncResource } = require('async_hooks');
4
5/**
6 * This benchmark verifies the performance of
7 * `AsyncLocalStorage.getStore()` on propagation through async
8 * resource scopes.
9 *
10 * - AsyncLocalStorage.run()
11 *  - AsyncResource.runInAsyncScope
12 *    - AsyncResource.runInAsyncScope
13 *      ...
14 *        - AsyncResource.runInAsyncScope
15 *          - AsyncLocalStorage.getStore()
16 */
17const bench = common.createBenchmark(main, {
18  resourceCount: [10, 100, 1000],
19  n: [1e4],
20});
21
22function runBenchmark(store, n) {
23  for (let i = 0; i < n; i++) {
24    store.getStore();
25  }
26}
27
28function runInAsyncScopes(resourceCount, cb, i = 0) {
29  if (i === resourceCount) {
30    cb();
31  } else {
32    const resource = new AsyncResource('noop');
33    resource.runInAsyncScope(() => {
34      runInAsyncScopes(resourceCount, cb, i + 1);
35    });
36  }
37}
38
39function main({ n, resourceCount }) {
40  const store = new AsyncLocalStorage();
41  runInAsyncScopes(resourceCount, () => {
42    bench.start();
43    runBenchmark(store, n);
44    bench.end(n);
45  });
46}
47