kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Cache PolymorphicSerializer in compiler-generated serializer

Open qwwdfsad opened this issue 3 years ago • 2 comments

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:

image

qwwdfsad avatar Apr 27 '22 11:04 qwwdfsad

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

qwwdfsad avatar Apr 27 '22 11:04 qwwdfsad

I think we have some caching by default, we just need to find out lay outs

sandwwraith avatar Apr 27 '22 12:04 sandwwraith

Expected in 1.8.20

shanshin avatar Dec 01 '22 11:12 shanshin