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

setImmediate vs setTimeout vs process.nextTick #69

Closed
Kikobeats opened this issue Mar 14, 2018 · 1 comment
Closed

setImmediate vs setTimeout vs process.nextTick #69

Kikobeats opened this issue Mar 14, 2018 · 1 comment

Comments

@Kikobeats
Copy link
Owner

Kikobeats commented Mar 14, 2018

   ┌───────────────────────┐
┌─>│        timers         │
│  └──────────┬────────────┘
│  ┌──────────┴────────────┐
│  │     I/O callbacks     │
│  └──────────┬────────────┘
│  ┌──────────┴────────────┐
│  │     idle, prepare     │
│  └──────────┬────────────┘      ┌───────────────┐
│  ┌──────────┴────────────┐      │   incoming:   │
│  │         poll          │<─────┤  connections, │
│  └──────────┬────────────┘      │   data, etc.  │
│  ┌──────────┴────────────┐      └───────────────┘
│  │        check          │
│  └──────────┬────────────┘
│  ┌──────────┴────────────┐
└──┤    close callbacks    │
   └───────────────────────┘
  • Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue.

  • Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes. It's slightly faster than setTimeout:

'use strict'

var bench = require('fastbench')

var run = bench([
  function benchSetImmediate (done) {
    setImmediate(done)
  },
  function benchNextTick (done) {
    process.nextTick(done)
  }
], 1024 * 1024)

// run them two times
run(run)

Considerations on browser side

  • on browser side, setImmediate/process.nextTick is not available.
  • A simple solution is setTimeout(fn, 0).
@Kikobeats
Copy link
Owner Author

Kikobeats added a commit that referenced this issue Mar 26, 2018
Kikobeats added a commit that referenced this issue Mar 26, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant