背景:
当我在写代码的时候AS有个提示:
Warning:Consider using `apply()` instead; `commit` writes its data to persistent storage immediately, whereas `apply` will handle it in the background
大体的意思就是:
尽量使用apply(),因为是异步的,commit()是同步的持久化存储
代码示例:
public void updateSpAsync() { SharedPreferences mySharedPreferences = getSharedPreferences("sp", MODE_PRIVATE); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putString("id", "this"); editor.putBoolean("isLogin", true); editor.apply(); } public void updateSp() { SharedPreferences mySharedPreferences = getSharedPreferences("sp", MODE_PRIVATE); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putString("id", "this"); editor.putBoolean("isLogin", true); boolean result = editor.commit(); }
总结:
1)效率上
在效率上,apply的效率比commit的效率高,因为apply是异步的,先将数据写入内存,然后写入磁盘;而commit是直接写入磁盘,我们知道写入磁盘的效率是比较低的
2)返回值
commit的方法是有返回值的,判断写入是否成功,而apply是没有返回值的
3)使用场景
尽量使用apply,而commit主要用在确保提交成功才有后续操作