在使用Lint检查代码时,得到提示
Consider using apply() instead; commit writes its data to persistent
storage immediately, whereas apply will handle it in the background
通过阅读文档得知只要区别在于:
- commit() API Level 1。apply() API Level 9。
- commit()有boolean返回值,确认是否写入数据成功。applay()无返回值。
- commit()立刻写入存储器中,apply立刻提交到内存中并在子线程中写入存储器。
因此,文档建议
If you don’t care about the return value and you’re using this from
your application’s main thread, consider using apply() instead.
因为在主线程中commit()会立刻执行写入存储器的耗时操作,而apply()在子线程中操作。
引用Lazy man’s algorithm的博客:
So commit() is an expensive operation,instead of blocking your method
waiting for the write to happen (which could take up to 100ms for
writing to the XML backed file in the background), it will drop
through in less than 5ms. The only thing you’ll lose is the return
value from commit() that lets you know if your write was successful or
not. but I bet you’re ignoring the boolean value returned from
commit() anyway.
如果不在意commit()返回结果,用apply()代替何乐不为呢?
引用文档地址:https://developer.android.com/reference/android/content/SharedPreferences.Editor.html
引用博客地址:https://nayaneshguptetechstuff.wordpress.com/2014/07/09/sharedpreferences-apply-vs-commit/