Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance Enhancement in EventEmitter’s emit Method #53056

Open
mertcanaltin opened this issue May 19, 2024 · 4 comments
Open

Performance Enhancement in EventEmitter’s emit Method #53056

mertcanaltin opened this issue May 19, 2024 · 4 comments
Labels
events Issues and PRs related to the events subsystem / EventEmitter.

Comments

@mertcanaltin
Copy link
Member

mertcanaltin commented May 19, 2024

What is the problem this feature will solve?

Specific problems addressed by this feature:

1.	Inefficient Error Handling:
 	The existing emit method combines error handling with regular event processing, causing unnecessary overhead even when no errors are involved.
2.	Redundant Checks and Operations:
 	The method contains multiple checks and operations that can be streamlined using modern JavaScript features like optional chaining (?.).
3.	Unnecessary Listener Array Cloning:
 	When multiple listeners are registered for an event, the current implementation clones the listener array, leading to unnecessary memory usage and processing time.
4.	Lack of Early Return Optimization:
 	The method does not leverage early returns effectively, resulting in extra processing steps that could be avoided when conditions are not met.

What is the feature you are proposing to solve the problem?

I propose a series of optimizations to the emit method in the EventEmitter class. These optimizations are designed to improve the performance and efficiency of event handling in Node.js. The proposed changes include:

1.	Separate Error Handling Logic:
	By handling errors early and separately from regular events, the overhead associated with error checking is reduced for non-error events.
2.	Utilize Optional Chaining (?.):
	Implementing optional chaining to simplify and speed up checks for null or undefined values within the event handling process.
3.	Direct Listener Invocation Without Cloning:
	Avoid unnecessary cloning of listener arrays by directly invoking listeners. This reduces memory usage and processing time, especially when multiple listeners are registered for the same event.
4.	Implement Early Return Statements:
	Introduce early returns to exit the function as soon as conditions are met, preventing unnecessary processing steps.

Proposed Changes to emit Method:

  • lib/events.js
EventEmitter.prototype.emit = function emit(type, ...args) {
  if (type === 'error') {
    const events = this._events;
    const handler = events?.error;
    if (!handler) {
      const err = args[0];
      if (err instanceof Error) {
        try {
          const capture = {};
          ErrorCaptureStackTrace(capture, EventEmitter.prototype.emit);
          ObjectDefineProperty(err, kEnhanceStackBeforeInspector, {
            __proto__: null,
            value: FunctionPrototypeBind(enhanceStackTrace, this, err, capture),
            configurable: true,
          });
        } catch {
          // If enhancing the error stack fails, continue without enhancement.
        }
        throw err; // Unhandled 'error' event
      }
      throw new ERR_UNHANDLED_ERROR(inspect(err));
    }
    if (typeof handler === 'function') {
      handler.apply(this, args);
    } else {
      const len = handler.length;
      for (let i = 0; i < len; ++i) {
        handler[i].apply(this, args);
      }
    }
    return true;
  }

  const events = this._events;
  if (!events) return false;

  const handler = events[type];
  if (!handler) return false;

  if (typeof handler === 'function') {
    handler.apply(this, args);
  } else {
    const len = handler.length;
    for (let i = 0; i < len; ++i) {
      handler[i].apply(this, args);
    }
  }
  return true;
};

Benefits of the Proposed Feature:

1.	Improved Performance:
	Reduces overhead for non-error events by handling errors separately and early.
	Decreases memory usage and processing time by eliminating unnecessary cloning of listener arrays.
2.	Cleaner and More Maintainable Code:
	Simplifies the codebase using modern JavaScript features like optional chaining.
	Introduces early returns for more readable and efficient code.
3.	Enhanced Efficiency:
	Optimizes event handling, particularly in applications with a high volume of events or complex event handling requirements.

These changes aim to enhance the overall performance and efficiency of the emit method in the EventEmitter class

What alternatives have you considered?

No response

@mertcanaltin mertcanaltin added feature request Issues that request new features to be added to Node.js. events Issues and PRs related to the events subsystem / EventEmitter. and removed feature request Issues that request new features to be added to Node.js. labels May 19, 2024
@bnb
Copy link
Contributor

bnb commented May 20, 2024

If you're confident in these changes, I'd highly recommend submitting a PR - easier and more in-line with our workflow to do code review that way 👍🏻

@Qard
Copy link
Member

Qard commented May 21, 2024

The listener cloning is important as a listener could within itself remove listeners that already triggered, and indeed "once" does this, which would result in array positions changing and still registered listeners could get skipped due to shifting past the position of the index into the array during the loop.

@mertcanaltin
Copy link
Member Author

The listener cloning is important as a listener could within itself remove listeners that already triggered, and indeed "once" does this, which would result in array positions changing and still registered listeners could get skipped due to shifting past the position of the index into the array during the loop.

To address this, I propose a conditional cloning approach. The listener array will only be cloned if a change (such as removal of the listener) is detected during event execution. In this way, can we avoid unnecessary cloning and still handle edge cases correctly I wonder if this approach will be performant

@simonkcleung
Copy link

Will it be still performant if there is only one event listener?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
events Issues and PRs related to the events subsystem / EventEmitter.
Projects
Status: Pending Triage
Development

No branches or pull requests

4 participants