Reflections on Reflection — Performance impact for a JSON parser on Android

Lessons on how to evaluate the viability of a software tool

“monkey looking at mirror” by Andre Mouton on Unsplash

JSON Libraries

{  
"id":1,
"name":"John Doe",
"age":21
}
class User(
val id: Long,
val name: String,
val age: Int
)

JSON.org

fun parseUserFromJson(string: String) = 
JSONObject(string).run {
User(
getLong("user"),
getString("name"),
getInt("age")
)
}

Gson

class User(
@SerializedName("id")
val id: Long,
@SerializedName("name")
val name: String,
@SerializedName("age")
val age: Int
)
fun parseUserFromJson(string: String) = 
Gson().fromJson<User>(string, User::class.java)

Immutables Type Adapters

@Gson.TypeAdapters
@Value.Immutable
interface User(
@get:SerializedName("id")
val id: Long,
@get:SerializedName("name")
val name: String,
@get:SerializedName("age")
val age: Int
)
fun parseUserFromJson(string: String) = GsonBuilder()
.registerTypeAdapterFactory(GsonAdaptersUser())
.create()
.fromJson(string, User::class.java)

Benchmarks

Protocol

Results

Nexus 6 API 23
Galaxy S8 API 24

Analysis

Understanding the cost of reflection

Developers shouldn’t judge the performance of a tool by a single criterion

Make sure you understand the difference between runtime and compile-time reflection

Performance should always be tested and quantified

Runtime performance isn’t everything

Android developer at Dashlane

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store