Performance implications of using Async Hooks

一世执手 提交于 2021-02-11 04:33:11

问题


I'm the author of a Node.js library and I want to use Async Hooks to improve DX. But I'm worried about performance.

I've read stories saying that everything is fine, as well as stories where performance was a blocker.

In theory, asynchronicity should only happen for IO operations and performance penality should be pretty much ~0. (As IO operations are several orders of magnitude more expensive than running JS code.)

But, in practice, does running extra JS on each async call induces a non-negligible performance degradation?

What is your experience with the performance of async hooks?

Use Case

The concrete use case is Wildcard API where I'm using Async Hooks which enables wonderful ergonomics for Wildcard users:

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>;

Thanks to Async Hooks, the Wildcard context is availble anywhere(!) within the lifecycle of the HTTP request.

Wildcard's async hook code is small but runs for each async call happening whithin the context of an HTTP request.

The main danger here are memory leaks but Wildcard's test suit is checking that there are no memory leaks.

来源:https://stackoverflow.com/questions/65702716/performance-implications-of-using-async-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!