joyent/node — comment on commit 4d4900fc65104604820c99faeaf439f958634451
File:  line 0
By herby:

or use two-array solution that does not copy data at all at the cost of slightly longer code and two more things (readPos, nextTickFront) to remember, like

var rl = nextTickFront.length, l = nextTickQueue.length;
if (rl > 0) {
try {
for (; readPos < rl; readPos++) {
nextTickFront[readPos]();
}
}
catch (e) {
readPos++;
if (readPos === rl) {
readPos = 0;
nextTickFront = nextTickQueue;
nextTickQueue = [];
if (nextTickFront.length) {
process._needTickCallback();
}
} else {
process._needTickCallback();
}
throw e; // process.nextTick error, or 'error' event on first tick
}
}

if (l === 0) return;

readPos = 0;
nextTickFront = nextTickQueue;
nextTickQueue = [];

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

(prematurely optimized, can be made simpler at the cost of nextTickFront hanging in memory or "unnecessary" _needTickCallback() included just for the purpose of "do the callback so it does the housekeeping in next tick, even if it will not have functions to call", in which case the inner of both catches will become simply

readPos++;
process._needTickCallback();
throw e;

and `if (l === 0) { return; }` will need to move up and take form of `if (l === 0 && rl === 0) { return; }` or the nextTickFront keeps hanging in memory)