Cost of monitor.subscribe

Hi all,
I know that the recommended way is to only subscribe to channels when necessary and unsubscribe when they are not needed anymore.
But what is actually the overhead of a subscription? Will it copy events per subscribed context?
What (if any?) is the downside of subscribing multiple times to a channel in a loop instead of e.g. doing it once during initialization?

The answer is “it depends”. The subscriptions are per context, but ref-counted per monitor. So calling monitor.subscribe again in the same context just increments a ref count. You will need a matching number of unsubscribes, if you want to do that.

If you are subscribing in a new context, then we will at least need to put a reference to that event on that context’s queue, and wake up the context to process it. For some event types that won’t be a copy, but for any type that’s potentially cyclic (that means anything with an ‘any’ in it - which is all Cumulocity types), then that will also mean a copy.

If you have a listener for it, then we will also have to execute some EPL. Whether that causes a copy depends whether your code is 100% statically analyzable to not mutate or escape the event from that method. Exactly how we determine that is too complex to explain here.

tl;dr - probably fine, but there are cases it might be an issue. For example, we have found that in some customer’s use cases (with both large MOs and very frequent), the bottleneck was copying those events onto a context’s queue.