I was wondering if anybody knows how setTimeout is implemented in node.js. I believe I have read somewhere that this is not part of V8. I quickly tried to find the implementation, but could not find it in the source(BIG).I for example found this timers.js file, which then for example links to timer_wrap.cc. But these file do not completely answer all of my questions.
- Does V8 have
setTimeout
implementation? I guess also from the source the answer is no. How is
setTimeout
implemented? javascript or native or combination of both? From timers.js I assume something along the line of both:var Timer = process.binding('timer_wrap').Timer;`
When adding multiple timers(setTimeout) how does node.js know which to execute first? Does it add all the timers to a collection(sorted)? If it is sorted then finding the timeout which needs to be executed is O(1) and O(log n) for insertion? But then again in timers.js I see them use a linkedlist?
- But then again adding a lot of timers is not a problem at all?
When executing this script:
var x = new Array(1000), len = x.length; /** * Returns a random integer between min and max * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var y = 0; for (var i = 0; i < len; i++) { var randomTimeout = getRandomInt(1000, 10000); console.log(i + ', ' + randomTimeout + ', ' + ++y); setTimeout(function () { console.log(arguments); }, randomTimeout, randomTimeout, y); }
you get a little bit of CPU usage but not that much?
- I am wondering if I implement all these callbacks one by one in a sorted list if I will get better performance?