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

Code before:
/**
 * Initializes a worker thread for a customized module loader.
 * @param {SharedArrayBuffer} lock - The lock used to synchronize communication between the worker and the main thread.
 * @param {MessagePort} syncCommPort - The message port used for synchronous communication between the worker and the
 * main thread.
 * @param {(err: Error, origin?: string) => void} errorHandler - The function to use for uncaught exceptions.
 * @returns {Promise<void>} A promise that resolves when the worker thread has been initialized.
 */
async function customizedModuleWorker(lock, syncCommPort, errorHandler) {
  let hooks;
  let initializationError;
  let hasInitializationError = false;

  {
    // If a custom hook is calling `process.exit`, we should wake up the main thread
    // so it can detect the exit event.
    const { exit } = process;
    process.exit = function(code) {
      if (hooks) {
        for (let i = 0; i < allThreadRegisteredHandlerPorts.length; i++) {
          const registeredPort = allThreadRegisteredHandlerPorts[i];
          registeredPort.postMessage(wrapMessage('exit', code ?? process.exitCode));
        }

        for (const { port, lock: operationLock } of unsettledResponsePorts) {
          port.postMessage(wrapMessage('exit', code ?? process.exitCode));
          // Wake all threads that have pending operations. Is that needed???
          AtomicsAdd(operationLock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
          AtomicsNotify(operationLock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
        }
      }
      syncCommPort.postMessage(wrapMessage('exit', code ?? process.exitCode));
      AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
      AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
      return ReflectApply(exit, this, arguments);
    };
  }


  try {
    hooks = await initializeHooks();
  } catch (exception) {
    // If there was an error while parsing and executing a user loader, for example if because a
    // loader contained a syntax error, then we need to send the error to the main thread so it can
    // be thrown and printed.
    hasInitializationError = true;
    initializationError = exception;
  }

  syncCommPort.on('message', handleMessage);


Review comment (performance):
nit: we should cache the result of `wrapMessage('exit', code ?? process.exitCode)` to reuse it in both loops (and outside the loops below)

Code after:

/**
 * Initializes a worker thread for a customized module loader.
 * @param {SharedArrayBuffer} lock - The lock used to synchronize communication between the worker and the main thread.
 * @param {MessagePort} syncCommPort - The message port used for synchronous communication between the worker and the
 * main thread.
 * @param {(err: Error, origin?: string) => void} errorHandler - The function to use for uncaught exceptions.
 * @returns {Promise<void>} A promise that resolves when the worker thread has been initialized.
 */
async function customizedModuleWorker(lock, syncCommPort, errorHandler) {
  let hooks;
  let initializationError;
  let hasInitializationError = false;

  {
    // If a custom hook is calling `process.exit`, we should wake up the main thread
    // so it can detect the exit event.
    const { exit } = process;
    process.exit = function(code) {
      const exitMsg = wrapMessage('exit', code ?? process.exitCode);
      if (hooks) {
        for (let i = 0; i < allThreadRegisteredHandlerPorts.length; i++) {
          const { port: registeredPort } = allThreadRegisteredHandlerPorts[i];
          registeredPort.postMessage(exitMsg);
        }

        for (const { port, lock: operationLock } of unsettledResponsePorts) {
          port.postMessage(exitMsg);
          // Wake all threads that have pending operations.
          AtomicsAdd(operationLock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
          AtomicsNotify(operationLock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
        }
      }
      syncCommPort.postMessage(exitMsg);
      AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
      AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
      return ReflectApply(exit, this, arguments);
    };
  }


  try {
    hooks = await initializeHooks();
  } catch (exception) {
    // If there was an error while parsing and executing a user loader, for example if because a
    // loader contained a syntax error, then we need to send the error to the main thread so it can
    // be thrown and printed.
    hasInitializationError = true;
    initializationError = exception;
  }