node/benchmark/async_hooks/async-local-storage-getstore-nested-resources.js
Chengzhong Wu 3000d77017
async_hooks: add async local storage propagation benchmarks
Add micro-benchmarks to verify the performance degradation related to
the number of active `AsyncLocalStorage`s.

With these benchmarks, trying to improve the async context propagation
to be an O(1) operation, which is an operation more frequent compared
to `asyncLocalStorage.run` and `asyncLocalStorage.getStore`.

PR-URL: https://github.com/nodejs/node/pull/46414
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
Reviewed-By: Minwoo Jung <nodecorelab@gmail.com>
2023-02-03 21:12:17 +00:00

47 lines
1.1 KiB
JavaScript

'use strict';
const common = require('../common.js');
const { AsyncLocalStorage, AsyncResource } = require('async_hooks');
/**
* This benchmark verifies the performance of
* `AsyncLocalStorage.getStore()` on propagation through async
* resource scopes.
*
* - AsyncLocalStorage.run()
* - AsyncResource.runInAsyncScope
* - AsyncResource.runInAsyncScope
* ...
* - AsyncResource.runInAsyncScope
* - AsyncLocalStorage.getStore()
*/
const bench = common.createBenchmark(main, {
resourceCount: [10, 100, 1000],
n: [1e4],
});
function runBenchmark(store, n) {
for (let i = 0; i < n; i++) {
store.getStore();
}
}
function runInAsyncScopes(resourceCount, cb, i = 0) {
if (i === resourceCount) {
cb();
} else {
const resource = new AsyncResource('noop');
resource.runInAsyncScope(() => {
runInAsyncScopes(resourceCount, cb, i + 1);
});
}
}
function main({ n, resourceCount }) {
const store = new AsyncLocalStorage();
runInAsyncScopes(resourceCount, () => {
bench.start();
runBenchmark(store, n);
bench.end(n);
});
}