Skip to content

Instantly share code, notes, and snippets.

@mmalecki
Created October 2, 2011 12:13
Show Gist options
  • Star 71 You must be signed in to star a gist
  • Fork 26 You must be signed in to fork a gist
  • Save mmalecki/1257394 to your computer and use it in GitHub Desktop.
Save mmalecki/1257394 to your computer and use it in GitHub Desktop.
process.nextTick vs setTimeout(fn, 0)
for (var i = 0; i < 1024 * 1024; i++) {
process.nextTick(function () { Math.sqrt(i) } )
}

Results

Intel i7 890 @ 2.93 GHz x64, node compiled with -march=native -mtune=native:

$ time node nextTick.js 

real	0m0.344s
user	0m0.276s
sys 	0m0.067s

$ time node setTimeout.js 

real	0m9.125s
user	0m8.707s
sys 	0m0.410s

Feel free to fork and add your results!

for (var i = 0; i < 1024 * 1024; i++) {
setTimeout(function () { Math.sqrt(i) }, 0)
}
@bedorlan
Copy link

@IngwiePhoenix The explanation is here: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick-vs-setimmediate

process.nextTick() allows you to "starve" your I/O events. setImmediate is safer.

@mutoe
Copy link

mutoe commented Oct 16, 2019

$ uname -a
Darwin MacBook-Pro.local 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64

$ node -v
v12.11.1

$ time node nextTick.js 
node nextTick.js  0.52s user 0.12s system 189% cpu 0.338 total

$ time node setTimeout.js 
node setTimeout.js  1.09s user 0.12s system 128% cpu 0.938 total

@kiwenlau
Copy link

on ubuntu virtual machine

time node nextTick.js

real	0m0.669s
user	0m0.487s
sys	0m0.357s


time node setTimeout.js

real	0m1.513s
user	0m1.709s
sys	0m0.090s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment