Is reading / writing preferences an expensive operation?

I have a preference that controls whether my application will play sound when the user presses 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 thought that reading preferences could be an expensive operation (similar to I / O, since preferences are saved), and that since the user presses the 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 often? If so, could there be another way, for example, registering a preference change listener to receive a notification when a preference changes?

+6
source share
2 answers

Honestly, I do everything that I do in the user interface thread, regardless of whether I need to do this, and I never noticed slight fluctuations even on slower devices. This is pretty damn fast. However, this is I / O, so doing it asynchronously, of course, will not be bad. For entries, if you are targeting API 9 or higher, you can use apply() instead of commit() , which does this asynchronously for you.

Regarding your question about the preference listener, yes, you can also do this:

 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 } } } 
+5
source

You can implement it in the memory cache using Java references. You can do the 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 minimizes the number of I / O operations.

0
source

All Articles