0

Adapters generated via codegen cannot be added in the Moshi.Builder().add(Type, JsonAdapter). So moshi doesn't know how to create the compile-time generated adapter. It uses reflection to create them, which adds a significant overhead on low-end devices in terms of latency.

is there a way to avoid this? Or should we just replace this with custom type adapters?

Archana Prabhu
  • 355
  • 4
  • 5
  • If you're using Moshi with codegen, there's no need to generate adapters using reflection. Every class you want to use for JSON-serialization should be annotated with `@JsonClass(generateAdapter = true)` and that's it. No overhead is present in this case. – user3738870 Aug 22 '22 at 16:15
  • 1
    @user3738870 Please refer to this https://github.com/square/moshi/issues/860. First comment on this issue - When using the moshi-kotlin-codegen kapt plugin, moshi still uses classname reflection to get the corresponding JsonAdapter at runtime. – Archana Prabhu Aug 22 '22 at 17:57
  • Oh that's true, I didn't know that. I don't think there's a way to completely avoid it, but it's cached so if you call it at startup for every adapter, it should be very fast after that. – user3738870 Aug 22 '22 at 18:45
  • 1
    I wanted to optimize it for the startup time itself. Hence I feel Moshi isn't the best option. Only way out of this is to have JsonFactory which knows how to create the adapter, instead of relying on reflection. – Archana Prabhu Aug 23 '22 at 03:14
  • 1
    Possibly. You can try kotlinx serialization instead: https://github.com/Kotlin/kotlinx.serialization – user3738870 Aug 23 '22 at 06:43
  • You could install the JsonAdapters manually, but you should really measure this on real devices. Class.classForName is extremely cheap and sometimes isn't even called on Moshi users' blocking/critical paths. – Eric Cochran Aug 24 '22 at 07:24
  • For a highly nested class, I observed high values for parsing. I could prevent reflection by creating a Factory(extended JsonAdapter.Factory) and the time reduced by 50% in release builds on actual devices. Quite happy with the perf of Moshi now. – Archana Prabhu Aug 24 '22 at 14:10

0 Answers0