重复使用 Android 共享首选项存储会影响性能吗?

is that repetitive use of Android Shared Preference storage make effect on performance?

我的应用程序使用 Android 服务中的 LocationListener 来频繁更新位置。应用程序将一些与位置过滤器相关的数据存储在共享首选项中。要求是尽可能频繁地更新位置。 我从监听器的 onLocationChanged 中的共享首选项中检索数据。 这是我的代码

public class MyLocationListener implements LocationListener {
    public void onLocationChanged(final Location loc) {
        sharedPreferences =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        int filterOne = sharedPreferences.getInt("filter_data",100);
        ------
        ------
        //code to process location with filter   
        ------
        ------ 
    }
}

使用上面的代码重复使用 sharedPreference。

我已经尝试将过滤器变量放在 onLocationChanged 之外,但是当服务重新启动时,值丢失并设置为零。

我只想知道这种做法好不好? 我应该使用其他选项吗?

Using above code sharedPreference is used in repetitive manner. I just want to know is that good practice or not?

以重复的方式访问 SharedPreferences 是没有问题的。但是,在您的情况下,每次事件触发时您都会重新初始化 sharedPreferences 。您应该只在 activity 的 onCreate 或片段的 onCreateView 中执行一次。

同样适用于 filterOne。如果该值是常量,因为它不会改变,您应该只在 onLocationChanged 调用之外检索它一次。


所以回答你的问题

is that repetitive use of Android Shared Preference storage make effect on performance?

是的,但只是因为你每次都重新初始化它。如果您听从我的建议,对性能几乎没有影响。