Optimize Parallel instance in GenSpawnInstances to avoid allocation.#4599
Optimize Parallel instance in GenSpawnInstances to avoid allocation.#4599nmichael44 wants to merge 1 commit into
Conversation
…Caches the and FunctionK instances in a private companion object using an Id cast.
|
Hi @durban, maybe you could review this one as well? In the same spirit as another one you did recently. There is also one more just like it right next to this one. |
|
I'm slightly nervous about the Have you observed the reduced memory footprint and GC overhead you write about? (I believe we have |
|
@durban I did not observe reduced memory -- I wasn't trying to solve a performance problem. I found these by reading the code of cats effect while trying to understand the framework better. Of all the ones you looked this is the one that could have the most impact since we build a natural transform for each element in the collection. But it's up to you. Maybe if I add some comment above the reference to the constant natural transform that would help convince you? |
Motivation
Currently in
GenSpawnInstances, theParallelinstance provides.paralleland.sequentialasdefs that instantiate anew (M ~> F)andnew (F ~> M)on every invocation.Because operations like
cats.Parallel.parTraverseinvokeP.parallel(ma)andP.sequential(ma)for every item in the collection, this creates a large number ofFunctionKobject allocations during a traversal, putting unnecessary pressure on the garbage collector.Changes
This PR eliminates these allocations by applying the
Idcaching technique (similar toResource.liftK).FunctionKinstances into aprivate object GenSpawnInstancesto act as true JVM-wide singletons (rather than trait fields).asInstanceOfto cast the cachedIdtransformations to the required effect type at the call site.Impact
Zero-allocation
parallelandsequentialtransformations for all effect types that implementGenSpawn. This reduces the memory footprint and GC overhead on hot paths involving parallel collections processing.