On Sat, Oct 3, 2015 at 6:00 PM, Andrea Giammarchi < andrea.giammar...@gmail.com> wrote:
> well > > > In fact, oftentimes the way people code uses closures which tend to be > more expensive than creating promises anyway. > > you pass "closures" to create a promise, a then and a catch, not sure > what you mean here. > > The Promise itself cannot be counted without counting the amount of > middle-callbacks needed to make it work, right? Am I misunderstanding that > sentence? > Apologies, I should have been more precise in my wording. By closures I did not mean anonymous functions. I meant functions that actually need to capture bindings from the outside environment. The cost of functions capturing their environment, at least in some modern engines, is bigger than the cost of allocating a promise. A lot of time, people write code like: ```js doFoo(function(err, data){ if(err) return callback(err); doBar(data, function(err, data2){ if(err) return callback(err); doBaz(data, function(err, data3){ if(err) return callback(err); callback(process(data3)); }); }); }); ``` Where each function needs to reference the outside variables of the function calling it and `doBaz` keeps a reference (at least in some current engines) to `data` although it does not actually need it. This is an optimizations engines can make in the future of course and not a penalty of callbacks themselves. With promises the code would be written as: ```js doFoo().then(doBar).then(doBaz); ``` And no variables would be captured (in current engines). Of course the callback version can also be flattened and written in a way that does not cause extra allocation: ```js doFoo(function(err, data){ if(err) return callback(err); doBar(data, handleBar); }); function handleBar(err, data2){ if(err) return callback(err); doBaz(data, handleBaz); } function handleBaz (err, data3){ if(err) return callback(err); callback(process(data3)); }; ``` This is however not how people write their code. So in regular code I find that callbacks in their regular usage are often slower than promises, and generators/coroutines often tend to be faster than both because of the flat writing style. I think Babel even performs this as an optimizations when it can prove it to be the case. Here is some (slightly outdated) material about how closures work in v8, I assume you don't need it, but I figured it would be good read for some of the list followers: http://mrale.ph/blog/2012/09/23/grokking-v8-closures-for-fun.html
_______________________________________________ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss