6

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Rahul J
  • 63
  • 3

1 Answers1

4

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.

Pawel
  • 15,548
  • 3
  • 36
  • 36
  • Do you think something like `apply` will come in DataStore? – Orcun Sevsay Mar 29 '22 at 12:27
  • 1
    @OrcunSevsay `apply` has a bunch of issues that datastore was made to circumvent, so I don't think so. What would you want to achieve by it anyway? – Pawel Mar 29 '22 at 13:09
  • 1
    @Pawel At start of application i try to check is user logged in or not. And Compose requires some default values for states. As a result i have login screen and after 1 second(Data store takes 1 second) i can display app content – Vetalll Jul 27 '22 at 16:42
  • @Vetalll I suggest you to start loading all the application interfaces and functions, assuming that user is logged in (since that is the most probable scenario) and then, when the Logged in status finally returned, you can either start doing remaining work with that info, or cancel the loading, finish the activity and open the signup/login activity. – Ezequiel Adrian May 04 '23 at 14:44