SharedPreferences.Editor中commit()和applay()的区别

编程知识 更新时间:2023-05-02 19:05:43

在使用Lint检查代码时,得到提示

Consider using apply() instead; commit writes its data to persistent
storage immediately, whereas apply will handle it in the background

通过阅读文档得知只要区别在于:

  1. commit() API Level 1。apply() API Level 9。
  2. commit()有boolean返回值,确认是否写入数据成功。applay()无返回值。
  3. 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/reference/android/content/SharedPreferences.Editor.html

引用博客地址:https://nayaneshguptetechstuff.wordpress/2014/07/09/sharedpreferences-apply-vs-commit/

更多推荐

SharedPreferences.Editor中commit()和applay()的区别

本文发布于:2023-04-28 04:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/bc21c83282294eea294ec9c1cf136767.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   Editor   SharedPreferences   applay   commit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 107668文章数
  • 27233阅读数
  • 0评论数