Bryan W
Bryan W

Reputation: 1167

Is this an efficient way to get/set multiple SharedPreferences in a singleton helper?

My Android app stores 15-20 settings pairs with SharedPreferences, and I've been using a helper class so I don't have to create a new method in every class that needs to retrieve them.

Some retrievals are starting to take >100ms, and I'm not sure my current method is efficient for performance since it passes in the Context and creates a new SharedPreferences object each time. This happens numerous times throughout the app's AsyncTasks.

Here's what I've been doing:

public class SharedPrefHelper {

static void setDefaults(String key, String value, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key, value);
    editor.apply();
}

static void setDefaultsInt(String key, int value, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putInt(key, value);
    editor.apply();
    }

    //... continued with other variable types and getDefault variants
    //....... 
} 

Would below be a more efficient way of handling this?

public class SharedPrefHelper {

private static SharedPreferences preferences;

static void init(@NonNull final App app) {
    preferences = PreferenceManager.getDefaultSharedPreferences(app);
}
//App is the Application class, init is called in onCreate()

static void setDefaults(String key, String value) {
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key, value);
    editor.apply();
    }
    //... continued with other variable types and getDefault variants
    //....... 
} 

Or are there other variable keywords that would do better (final, etc)?

Upvotes: 0

Views: 39

Answers (1)

LppEdd
LppEdd

Reputation: 21134

+100ms is a long time for such a simple action and so little key-value pairs.
I think the problem is not here.

However, to answer your question, yes, the proposed alternative is certainly better than the original one. Indeed, there is no point in calling getDefaultSharedPreferences(context) multiple times, as that method points to a default file, which is set application-wide.

So just store it as instance/static field (but avoid static as much as possible).


preferences.edit()

returns a new, fresh, Editor (EditorImpl, it maintains a Map of the changed key-value pairs and then persist everything on apply) every call, so you're totally fine.

Upvotes: 1

Related Questions