square / moshi

A modern JSON library for Kotlin and Java.
https://square.github.io/moshi/1.x/
Apache License 2.0
9.78k stars 761 forks source link

Init of Adapter at "runtime" takes more time than actual parsing. #1570

Open ArchanaPrabhu opened 2 years ago

ArchanaPrabhu commented 2 years ago

I am aware that in order to use the generated JsonAdapters without "reflection", we need to create a JsonAdaptor.Factory that maps the <Type, JsonAdapter>. (If we do not use a factory to provide, Moshi internally uses reflection to find these generated classes -> "Class.forName()", which can add to the latency)

In order to finally parse a string, we need to get the JsonAdapter from the Moshi instance and call fromJson.

Observations It takes a long time to create the JsonAdapter for the very first time. I could see that JsonReader$Options.of is taking considerable time.

Screenshot 2022-08-26 at 10 20 31 AM

My metrics after migration to Moshi looks like this : Time taken to create adapter : 100 ms Time taken to parse : 30 ms

(Previous code) time taken by GSON : 70 ms

Since 130 ms > 70 ms, I do not actually see the gains here. I understand that the cost of adapter creation is one time, but I am optimizing for app launch.

I do not see anyway to reduce the adapter creation time as well. I think we should consider optimizing adapter creation latency.

ZacSweers commented 2 years ago

This needs more information

In general, if startup is this critical to your path, you should likely write your own custom adapters that are optimized for the data coming in. For example, if you only have a couple of keys, it could be not worth the up-front tradeoff to use okio.Options like this chart is doing.

ArchanaPrabhu commented 2 years ago

Thanks for responding.

  1. Moshi Version : 1.13.0
  2. I have not used any adapter with GSON, so it parses by reflection.
  3. GSON uses reflection, trace for the same.
Screenshot 2022-08-27 at 9 38 38 AM

Yes, then I guess custom adapters are the way to go here.