Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
process: optimize process.nextTick()
Browse files Browse the repository at this point in the history
33% performance boost on large nextTick queues.
  • Loading branch information
bnoordhuis committed Oct 31, 2011
1 parent 5fee1ff commit 4d4900f
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions src/node.js
Expand Up @@ -185,20 +185,18 @@
var l = nextTickQueue.length;
if (l === 0) return;

var q = nextTickQueue;
nextTickQueue = [];

try {
for (var i = 0; i < l; i++) {
nextTickQueue[i]();
}
for (var i = 0; i < l; i++) q[i]();
}
catch (e) {
nextTickQueue.splice(0, i + 1);
if (i + 1 < l) {
if (nextTickQueue.length) {
process._needTickCallback();
}
throw e; // process.nextTick error, or 'error' event on first tick
}

nextTickQueue.splice(0, l);
};

process.nextTick = function(callback) {
Expand Down

2 comments on commit 4d4900f

@koichik
Copy link

@koichik koichik commented on 4d4900f Nov 1, 2011

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bnoordhuis - If a callback throws an exception, the following callbacks of q are never called (testcase is here).
The remaining callbacks must be concatenated before nextTickQueue.

       catch (e) {
+        if (i + 1 < l) {
+          nextTickQueue = q.slice(i + 1).concat(nextTickQueue);
+        }
         if (nextTickQueue.length) {

@bnoordhuis
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll take @koichik's patch. This commit is phase 1 of a two-pronged attack on getting rid of the O(n) calls to process._needTickCallback() because that's the real performance drain. Dropping the Array.splice() is just icing on the cake.

Please sign in to comment.