javascript - NodeJS - setTimeout(fn,0) vs setImmediate(fn) -


what difference between two, , when use 1 on other?

settimeout calling function after delay has finished. whenever function called not executed immediately, queued executed after executing , queued eventhandlers finish first. settimeout(,0) means execute after current functions in present queue executed. no guarantees can made how long take.

setimmediate similar in regard except doesn't use queue of functions. checks queue of i/o eventhandlers. if i/o events in current snapshot processed, executes callback. queues them immedieately after last i/o handler process.nexttick. faster.

also (settimeout,0) slow because check timer @ least once before executing. @ times can twice slow. here benchmark.

var suite = require('benchmark').suite var fs = require('fs')  var suite = new suite  suite.add('deffered.resolve()', function(deferred) {   deferred.resolve() }, {defer: true})  suite.add('setimmediate()', function(deferred) {   setimmediate(function() {     deferred.resolve()   }) }, {defer: true})  suite.add('settimeout(,0)', function(deferred) {   settimeout(function() {     deferred.resolve()   },0) }, {defer: true})  suite .on('cycle', function(event) {   console.log(string(event.target)); }) .on('complete', function() {   console.log('fastest ' + this.filter('fastest').pluck('name')); }) .run({async: true}) 

output

deffered.resolve() x 993 ops/sec ±0.67% (22 runs sampled) setimmediate() x 914 ops/sec ±2.48% (57 runs sampled) settimeout(,0) x 445 ops/sec ±2.79% (82 runs sampled) 

first 1 gives idea of fastest possible calls. can check if settimeout gets called half many times other. remember setimmediate adjust filesystem calls. under load perform less. don't think settimeout can better.

settimeout un-intrusive way of calling functions after time. its in browser. may not suited server-side (think why used benchmark.js not settimeout).


Comments

Popular posts from this blog

C# random value from dictionary and tuple -

cgi - How do I interpret URLs without extension as files rather than missing directories in nginx? -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -