-
-
Notifications
You must be signed in to change notification settings - Fork 31.6k
lib: Enhancing Performance and Readability with Switch Statements 🚀 #51281
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
lib: Enhancing Performance and Readability with Switch Statements 🚀 #51281
Conversation
Hi! Thanks for this PR, could you please add benchmarks for it? Looking good so far Please consider reading the contributing guidelines https://github.com/nodejs/node/blob/main/doc/contributing/pull-requests.md#the-process-of-making-changes |
|
This comment was marked as off-topic.
This comment was marked as off-topic.
This does not mean anything, you're not testing Node.js, and you're not even testing the same code. |
I am extremely sorry |
@sanjaiyan-dev Thanks for the PR. Some recommendations to improve your PR:
@aduh95 We already have a benchmark for buffers read (I will trigger once the lint is fixed), I don't think that's necessary to have a micro-benchmark for if/else statements. We also have other places with perf sensitive in the code that use a switch instead of if statements. Something that maybe could affect/help is the position of each comparison, what is more common to read, |
I will make the requested changes as soon as possible. Apologies for any inconvenience caused. |
Hi, this PR will result in a very minimal performance improvement by changing from multiple if conditions to a switch statement. Since a switch statement utilizes a branch table (correct me if I'm wrong), the gain in performance will be marginal, but it enhances code readability.
I've attached a picture of the JavaScript benchmark I ran, and there's a YouTube video demonstrating how a switch statement can lead to performance gains. The video showcases how the C compiler optimizes switch statements, and if I'm correct, this optimization principle should also apply to the V8 engine, which JIT compiles JavaScript to assembly language: YouTube link.