Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - Promise vs Observable - performance context

I have an Angular 5 site that receives data from a REST API, something like 1-4 requests to the API each page, and what happens is that the requests sometimes take a long time(and sometimes not).

Now, all the requests are being performed in one function using Observable :

return this.http.post(url, {headers: this.header})
        .map(res => res.json())      
        .catch(this.handleError)

my question is - could it be that the slow process is happening because an Observable is being used? Would Promises will be better for the performance? Or is there no difference between an Observable and a Promise in performance context?

like image 354
levi Avatar asked Jan 17 '19 11:01

levi


1 Answers

because you question intrigue me. i have create same testing which look like this :

console.time('observable');
for(let i = 0; i < 10000; i++) {
  let user$ = of({
    name: 'yanis-git'
  });

  user$.subscribe(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('observable');

console.time('promise');
for(let i = 0; i < 10000; i++) {
  new Promise((resolve) => {
    resolve({
      name: 'promise'
    });
  }).then(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('promise');

and result looks like this (can be different on your browser / setup but proportion should be the same :

observable: 34.060791015625ms
promise: 103.4609375ms

EDIT :

Another implementation with both async traitment inside :

console.time('observable');
for(let i = 0; i < 10000; i++) {
  let user$ = Observable.create((o) => {
    setTimeout(() => {
      o.next({
        name: 'observable'
      });
    });
  });

  user$.subscribe(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('observable');

console.time('promise');
for(let i = 0; i < 10000; i++) {
  new Promise((resolve) => {
    setTimeout(() => resolve({
      name: 'promise'
    }))
  }).then(user => {
    // do something. Prefer not console.log because is ressource consuming.
  });
}
console.timeEnd('promise');

Result are close but race are win by observable.

observable: 160.162353515625ms
promise: 213.40625ms

live sample

if you want to check on stackblitz, please use real browser console to see timer output

like image 196
Yanis-git Avatar answered Sep 28 '22 06:09

Yanis-git