Repository: nodejs/node
File: lib/internal/modules/esm/worker.js (JavaScript)

Code before:
  function registerHandler(toWorkerThread) {
    toWorkerThread.on('message', handleMessage);
    ArrayPrototypePush(allThreadRegisteredHandlerPorts, toWorkerThread);
  }

  function getMessageHandler(method) {
    if (method === '#registerWorkerClient') {
      return registerHandler;
    }
    return hooks[method];
  }

  /**
   * Handles incoming messages from the main thread or other workers.
   * @param {object} options - The options object.
   * @param {string} options.method - The name of the hook.
   * @param {Array} options.args - The arguments to pass to the method.
   * @param {MessagePort} options.port - The message port to use for communication.
   * @param {Int32Array} options.lock - The shared memory where the caller expects to get awaken.
   */
  async function handleMessage({ method, args, port, lock: msgLock }) {
    // Each potential exception needs to be caught individually so that the correct error is sent to
    // the main thread.
    let hasError = false;
    let shouldRemoveGlobalErrorHandler = false;
    assert(typeof getMessageHandler(method) === 'function');
    if (port == null && !hasUncaughtExceptionCaptureCallback()) {
      // When receiving sync messages, we want to unlock the main thread when there's an exception.
      process.on('uncaughtException', errorHandler);
      shouldRemoveGlobalErrorHandler = true;
    }
    const usedLock = msgLock ?? lock;

    // We are about to yield the execution with `await ReflectApply` below. In case the code
    // following the `await` never runs, we remove the message handler so the `beforeExit` event
    // can be triggered.
    syncCommPort.off('message', handleMessage);

    // We keep checking for new messages to not miss any.
    clearImmediate(immediate);
    immediate = setImmediate(checkForMessages).unref();

    const unsettledActionData = { port: port ?? syncCommPort, lock: usedLock };

    unsettledResponsePorts.add(unsettledActionData);

    let response;
    try {
      response = await ReflectApply(getMessageHandler(method), hooks, args);
    } catch (exception) {
      hasError = true;

Review comment (performance):
maybe cache result of `getMessageHandler(method)` here and reuse it below.

Code after:
   */
  function registerHandler(toWorkerThread, registeredThreadId) {
    toWorkerThread.on('message', handleMessage);
    ArrayPrototypePush(allThreadRegisteredHandlerPorts, { port: toWorkerThread, registeredThreadId });
  }

  /**
   * @callback registerHandler
   * @param {number} unregisteredThreadId - the thread id of the worker thread that is being unregistered
   * from the Hooks Thread
   */
  function unregisterHandler(unregisteredThreadId) {
    allThreadRegisteredHandlerPorts = ArrayPrototypeFilter(
      allThreadRegisteredHandlerPorts, (el) => el.registeredThreadId !== unregisteredThreadId);
  }

  function getMessageHandler(method) {
    if (method === '#registerWorkerClient') {
      return registerHandler;
    }
    if (method === '#unregisterWorkerClient') {
      return unregisterHandler;
    }
    return hooks[method];
  }

  /**
   * Handles incoming messages from the main thread or other workers.
   * @param {object} options - The options object.
   * @param {string} options.method - The name of the hook.
   * @param {Array} options.args - The arguments to pass to the method.
   * @param {MessagePort} options.port - The message port to use for communication.
   * @param {Int32Array} options.lock - The shared memory where the caller expects to get awaken.
   */
  async function handleMessage({ method, args, port, lock: msgLock }) {
    // Each potential exception needs to be caught individually so that the correct error is sent to
    // the main thread.
    let hasError = false;
    let shouldRemoveGlobalErrorHandler = false;
    const messageHandler = getMessageHandler(method);
    assert(typeof messageHandler === 'function');
    if (port == null && !hasUncaughtExceptionCaptureCallback()) {
      // When receiving sync messages, we want to unlock the main thread when there's an exception.
      process.on('uncaughtException', errorHandler);
      shouldRemoveGlobalErrorHandler = true;
    }
    const usedLock = msgLock ?? lock;

    // We are about to yield the execution with `await ReflectApply` below. In case the code
    // following the `await` never runs, we remove the message handler so the `beforeExit` event
    // can be triggered.