Is Reading / Writing Preferences An Expensive Operation?
Asked Answered
C

2

6

I have a preference that controls whether or not my app plays a sound whenever the user clicks a button (which is done quite often, think of a calculator). Each time the user clicks the button the following method is called:

private void playButtonClickSound() {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(parentActivity);
    boolean sounds = sharedPrefs.getBoolean("prefSounds", false);
    if (sounds) {
        // blah
    }
}

I was thinking that reading preferences might be an expensive operation (similar to an I/O operation because preferences are persisted) and that since the user clicks buttons so often it might be a bad idea to do it this way.

In general is it a bad idea to read/write preferences frequently? If so, might there be another way such as registering a preference change listener to get notified when a preference changes?

Cressler answered 19/3, 2013 at 5:7 Comment(0)
C
5

Frankly I do all of mine on the UI thread, whether or not I should, and I've never noticed a slight amount of hesitation even on slower devices. It's pretty damn quick. That said, it is I/O, so doing it asynchronously certainly wouldn't be a bad thing. For writes, if you're targeting API 9 and above, you can use apply() instead of commit() which does it asynchronously for you.

As for your question on a preference change listener, yes you can do that as well:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
    @Override
    public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
        if("my_preference_key".equals(key) {
            //Handle it here
        }
    }
}
Calix answered 19/3, 2013 at 5:25 Comment(1)
Great that's how I will do it in the future. :)Cressler
M
0

You can implement in memory cache using Java References. You can do following

public boolean getMySound(){
     boolean sound=getFromMemory();
     if (!sound){//if not available 
          //lets load from shared preferences
     sound=getSoundFromPreference();
         // update memory cache so next time i will load from memory
    addToMemory(sound);
    }
    return sound;
}

This will minimize number of I/O operation.

Malisamalison answered 19/3, 2013 at 5:22 Comment(1)
I was thinking about doing that exact kind of thing!Cressler

© 2022 - 2024 — McMap. All rights reserved.