KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
So, I've been thinking about a brain teaser - what if I had a large object I for some reason had to iterate through in node js, and didn't want to block the event loop while I was doing that? Here's an off-the-top-of-my-head example, I'm sure it can be much cleaner: var forin = function(obj,callback){ var keys = Object.keys(obj), index = 0, interval = setInterval(function(){ if(index < keys.length){ callback(keys[index],obj[keys[index]],obj); } else { clearInterval(interval); } index ++; },0); } While I'm sure there are other reasons for it being messy, this will execute slower than a regular for loop, because setInterval 0 doesn't actually execute every 0 ms, but I'm not sure how to make a loop with the much faster process.nextTick. In my tests, I found this example takes 7 ms to run, as opposed to a native for loop (with hasOwnProperty() checks, logging the same info), which takes 4 ms. So, what's the cleanest/fastest way to write this same code using node.js?
Tags (comma-separated)
Save Edits
Cancel