According to my tests, a Promise is more performant than an Observable.
I think Yanis-git test is a good start, but only shows part of the picture. It only calculates the starting of the Promise or Observable, but doesn't count the time for its resolution.
Here is the code I modified to take into account the resolution of the async functions as well:
https://stackblitz.com/edit/typescript-xhhseh?file=index.ts
import { of, Observable, zip } from 'rxjs';
console.clear();
function testPromise(){
console.time('promise');
const promiseAry = [];
for(let i = 0; i < 10000; i++) {
promiseAry[i] = new Promise((resolve) => {
setTimeout(() => resolve({
name: 'promise'
}))
}).then(user => {
// do something. Prefer not console.log because is ressource consuming.
});
}
Promise.all(promiseAry).then(() =>{
console.timeEnd('promise');
// test Observables after Promises have completed
testObservable();
})
}
function testObservable(){
console.time('observable');
const observeAry = [];
for(let i = 0; i < 10000; i++) {
observeAry[i] = Observable.create((o) => {
setTimeout(() => {
o.next({
name: 'observable'
});
});
});
observeAry[i].subscribe(user => {
// do something. Prefer not console.log because is ressource consuming.
});
}
let source$ = zip(...observeAry);
source$.subscribe(([weatherInfo, tweetInfo]) =>
console.timeEnd('observable')
);
}
testPromise();
When I run the test in Chrome (on Mac), by visiting this page directly and opening the console: https://typescript-xhhseh.stackblitz.io/ I get these results:
promise: 279.65185546875ms
observable: 552.891845703125ms
And a very similar result in Firefox:
promise: 232ms - timer ended
observable: 319ms - timer ended
Running them repeatedly, I always come up with Observable taking more time than Promise, which makes sense especially because Promises are now native to JavaScript, whereas Observables are not, so they wouldn't seem to be as performant.
Special thanks to Yanis-git for coming up with the original test that I forked.