问题描述
我是一个 Node.js 库的作者,我想使用 Async Hooks 来改进 DX。但我担心性能。
我读过说一切都很好的故事,也读过表现阻碍的故事。
理论上,异步性应该只发生在 IO 操作中,而性能惩罚应该几乎是 ~0。 (因为 IO 操作比运行 JS 代码要昂贵几个数量级。)
但是,实际上,在每个异步调用上运行额外的 JS 是否会导致不可忽略的性能下降?
您对异步钩子的性能有何体验?
用例
具体用例是 Wildcard API,其中我使用了 Async Hooks,它为通配符用户提供了出色的人体工程学设计:
const { server } = require("@wildcard-api/server");
const { context } = require("@wildcard-api/context");
const db = require("./path/to/db");
// Server endpoint for user login
server.login = async (userEmail,password) => {
if (!checkCredentials(userEmail,password)) {
return { wrongCredentials: true };
}
const { userId,userName } = await db.getUser(userEmail);
// Context modifications are persisted. (Under the hood,// Wildcard uses Cookies to persist the context.)
context.user = {
userId,userName,};
};
// Server endpoint to get the to-do list of the logged-in user.
server.getTodoList = async () => {
// `context.userId` is available here!
const { userId } = context;
if (!userId) {
return { notLoggedIn: true };
}
const todos = await db.getTodoList(userId);
return todos;
};
// The neat thing here is that the following also works:
<div>
{/* ... */}
{/* Somewhere deep in a React tree... */}
{/* ... */}
<Header>
{
// The Wildcard `context` is availble here!
// Thanks to async hooks,Wildcard kNows to which
// HTTP request `context` belongs too. (While doing SSR.)
context.userId ? <SignIn /> : <logout />
}
</Header>;
</div>;
感谢 Async Hooks,通配符 context
在 HTTP 请求的生命周期内的任何地方(!)都可用。
Wildcard 的异步钩子 code is small 但为 每个 在 HTTP 请求上下文中发生的异步调用运行。
这里的主要危险是内存泄漏,但 Wildcard 的测试套件正在检查是否存在内存泄漏。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)