I was checking the execution time of datastore and shared preference and I observed that datastore takes more time than shared preference.
This is my code
suspend fun saveUser(user: User, context: Context) {
val userString =
Json.encodeToString(User.serializer(), user)
val time1 = System.nanoTime()
context.dataStore.edit { preferences ->
preferences[PreferencesKeys.USER] = userString
}
val time2 = System.nanoTime()
with(userPref.edit()) {
putString(HOME_USER_KEY, userString)
apply()
}
val time3 = System.nanoTime()
println("Time taken")
println("Datastore : ${time2 - time1}")
println("Shared Preferences : ${time3 - time2}")
}
And the output
I/System.out: Time taken
I/System.out: Datastore : 208257769
I/System.out: Shared Preferences : 14458539
I/System.out: Time taken
I/System.out: Datastore : 2892692
I/System.out: Shared Preferences : 246462
I/System.out: Time taken
I/System.out: Datastore : 3043770
I/System.out: Shared Preferences : 293846
I/System.out: Time taken
I/System.out: Datastore : 5548077
I/System.out: Shared Preferences : 321846
I/System.out: Time taken
I/System.out: Datastore : 2344076
I/System.out: Shared Preferences : 208616
Any idea of why this might be happening?
Because data store has additional layers of thread safety - in this case edit { }
is suspending function that switches the dispatcher "under the hood" and waits until the disk write is actually complete.
SharedPreferences apply
doesn't do that - it stores changes in-memory while starting async disk write that you don't have control over nor can you handle any errors.