I showed several solutions to computing factorial using asynchronous methods in Factorial using promises. Two of the solutions used native ES6 promises and generators. I wanted to find out which one is faster.
Setup
Chrome v8 natively supports both features. I started with a simple page and performance profile calls.
1 |
|
Here are the two solutions
1 | function* Factorial() { |
Performance profile
Open this page in Chrome (I have v40) and be surprised by the huge difference in performance. The solution using promises takes 1 second.
The solution using generator function takes 7 milliseconds.
JsPerf
I was so surprised by this difference that I wanted another confirmation. I posted the same
code to jsperf website and ran the tests on Chrome, Chrome Canary and Firefox.
The results confirmed that using a single generator function is much much faster than creating a
long chain of promises and executing a large number of .then
callbacks.
You can run the test yourself at jsperf.com/v8-generators-vs-promises
Conclusion
Promises are powerful, but there is a performance penalty to using them. There are ways to use generators AND promises together to minimize the penalty, see Going Async With ES6 Generators by Kyle Simpson.