#Performance of multiple subscribers vs one subscriber

10 messages · Page 1 of 1 (latest)

boreal elm
#

Lets say I have an observable and if that emits a new value, I need to update 20 objects. I could either create one big subscription, that iterates through an array that holds those objects, and then modifies them. Or I could do one subscription for each object, that does a singular update of the current one.

Would one of those variants be faster than the other, or are they equally in terms of performance?

placid stream
boreal elm
placid stream
#

i would think the same, but i'm not sure

flat spire
#

having one big object and JS beeing single threaded means that that the app will be blocked for a greater amount of time.
With multiple subscriptions the load will be splitted in many small task but you have an overhead.

but at the and every modern device is really really fast and you would not see a noticable difference. Maybe if you have 1'000'000 object or so it would matter...
My advice is: do some clean and readable coding! performance doesn't matter 99% of the time

boreal elm
weak tree
#

An observable is just an array over time. You can think of these two examples as equivalent

of([1,2,3]).subscribe(arr => {
  for (const item of arr) {
    console.log(item)
  }
})
from([1,2,3]).subscribe(arr => {
  console.log(item)
})
#

but when you subscribe multiple times, you need to think about what you're subscribing to. It could be very inefficient to subscribe to an observable 20 times if it does some expensive computation. If you expect multiple subscribers you usually want to share() the observable first.

#
const source = new Observable((subscriber) => {
  const interval = setInterval(() => {
    subscriber.next()
  }, 1000)
  return () => clearInterval(interval)
})
for (let i=0; i < 1000; i++) {
  source.subscribe()
}

This would be very slow since it would create 1000 timers. In this case you should multicast the observable

const shared = source.pipe(share())

for (let i=0; i < 1000; i++) {
  shared.subscribe()
}

Now only one timer will be created, and shared across all subscribers.

#

To learn more look up the difference between hot/cold and unicast/multicast observables