With any performance question the best rule of thumb is "Try it with the profiler to be sure". If you suspect a performance issue then run some tests in Instruments.
Answering your question in general is difficult without a deep investgation into how Apple has implemented any Publisher
and AnyPublisher
. In my experience this kind of type erasure involves, abstractly speaking, taking a fully typed entity and putting in a "box", that is, wrapping it up inside a level of indirection.
Any code that wants to access the thing inside the box has to go through that level of indirection. This extra level will probably have a (small) cost in terms of absolute performance in both call time and memory.
In contrast, using some Publisher
would most commonly happen when you have a generic function: func doSomething<T: somePublisher>(firstArg: T)
. In this case the compiler will generate a specific version of doSomething
for each type. I would expect there to be no extra level of indirection so call time should not be affected. But your code will be larger.
The most "efficient" way for you to test it yourself will be to use the broilers in Instruments. You are bound to run into trade-offs between memory-size and runtime speed... it's a classic computer science problem.
And for what it's worth, Apple themselves have warned against the potential performance penalties of using existentials (i.e. any <Protocol>
). Their advice is the same you're getting here though - if you're concerned about it, use the profiler.