kotlinx.serialization
                                
                                 kotlinx.serialization copied to clipboard
                                
                                    kotlinx.serialization copied to clipboard
                            
                            
                            
                        Cache PolymorphicSerializer in compiler-generated serializer
Currently, for the serializable class with polymorphic property, e.g.
@Serializable
data class PolymorphicWrapper(val i: @Polymorphic Poly)
nested write$self contains the following snippet:
output.encodeSerializableElement(serialDesc, 0, new PolymorphicSerializer(Reflection.getOrCreateKotlinClass(PurePolymorphismOverheadBenchmark.Poly.class)), self.i);
The problem is that PolymorphicSerializer instantiated every time deserialize is invoked instead of being cached in an outer field.
It leads to a serious performance impact because PolymorphicSerializer has non-trivial cost in its constructor: descriptor instantiation is a dominating factor in a polymorphic benchmark, see screenshot attached:
 
                                    
                                    
                                    
                                
I believe this is third or fourth time we have a problem with non-cacheable serializer.
@sandwwraith maybe it's time to revisit internal code-gen and just prohibit any non-cacheable serializers on encode/decode code paths, as profiling and eliminating each individual one is quite cumbersome.
Additionally, we'll reduce number of allocations this way, which usually worth it
I think we have some caching by default, we just need to find out lay outs
Expected in 1.8.20