4 ms·
This article is misinformed... I don't know where to start. As others have said, the shallow nature of his argument is indicated by the complete avoidance of e
by jlongster 13y ago
This article is misinformed... I don't know where to start.
As others have said, the shallow nature of his argument is indicated by the complete avoidance of error handling. Callbacks spin out of control very quickly, not because you have to handle every single callback, but you have to handle an error at every single point as well. Mix in some more advanced control flows like `map`, and it's insane.
Please, please do not heed advice to "not use function closures". That's completely ridiculous and unrelated to callbacks. Every single one of his tests creates a new function for every single iteration. Of course that's terrible if you are iterating 2e4 times. Over here in the real world, my closures are executed oh, about 100 times a second (e.g. completely negligible perf hit). This is a seriously flawed benchmark.
I've seen that a common argument for solving callback hell is to move all the functions up into the same scope and name them. I have no idea how you handle that in real code. It's hard enough to keep track of it in normal callback-style, but forcing me to jump around and create tons of temporary names sounds insane.
Learn you some functional programming, and why it's good. Also learn you some error handling, promises, and why callbacks are terrible.
(note: remember folks, async code is async for a reason. It needs to go fetch data from something very slow, like a network connection or hard disk. It's so silly to benchmark closure creation for IO-bound apps.)
- trevnorris 13y ago> my closures are executed oh, about 100 times a second (e.g. completely negligible perf hit). This is a seriously flawed benchmark. Take Node's case where you're accepting HTTP requests. Each request is going to require a new instance, and call into the connection listener. If the connection listener contains all the function declarations for all events attached to the client then you loose the performance you could have had by v8 using a previously optimized function. The benchmark was intentionally made to show worst case. I don't expect every application to magically run 80% faster just because they moved some function declarations around.
- simonster 13y agoI'm actually surprised at how low the cost of function declarations is. V8 can handle millions of function declarations per second (as you know http://jsperf.com/closure-vs-callback/8 http://jsperf.com/closure-vs-callback/8). The cost is so low that ArraySort in http://code.google.com/p/v8/source/browse/trunk/src/array.js http://code.google.com/p/v8/source/browse/trunk/src/array.js, which implements Array.prototype.sort() in V8, declares 6 functions inside a function. Sure, you shouldn't define functions in tight loops, but otherwise this seems like unnecessary optimization.