博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SharedPreferences.Editor 的apply()与commit()方法的区别
阅读量:4600 次
发布时间:2019-06-09

本文共 2085 字,大约阅读时间需要 6 分钟。

commit()的文档

官方文档如下:

Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

Note that when two editors are modifying preferences at the same time, the last one to call commit wins.

If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead.

apply()的文档

官方文档如下:

Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

Note that when two editors are modifying preferences at the same time, the last one to call apply wins.

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

You don't need to worry about Android component lifecycles and their interaction with apply() writing to disk. The framework makes sure in-flight disk writes from apply() complete before switching states.

解释说明

  1. 需要注意的是commit()方法是Added in API level 1的,也就是sdk1就已经存在了.
  2. apply()方法是Added in API level 9的.
  3. commit()有返回值,成功返回true,失败返回false.commit()方法是同步提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。
  4. apply()没有返回值.apply()是将修改的数据提交到内存, 而后异步真正的提交到硬件磁盘.

为什么建议使用apply()替代commit() ?

答:因为Android的设计人员发现,开发人员对commit的返回值不感兴趣,而且在数据并发处理时使用commit要比apply效率低,所以推荐使用apply.

posted on
2017-05-08 10:57  阅读(
...) 评论(
...) 收藏

转载于:https://www.cnblogs.com/zhaodahai/p/6824007.html

你可能感兴趣的文章
Coursera公开课笔记: 斯坦福大学机器学习第十课“应用机器学习的建议(Advice for applying machine learning)”...
查看>>
竞价广告系统-广告检索
查看>>
强哥PHP面向对象学习笔记
查看>>
[转]基于.NET平台常用的框架整理
查看>>
Symbian (Read Inbox)读取收件箱的内容
查看>>
良好的编程规范
查看>>
struts2 入门
查看>>
.net 编译原理
查看>>
mean 快速开发和现有技术的对比分析
查看>>
Metro Style app :浏览器扩展
查看>>
linux的kernel是怎样工作的(TI_DM36X_ARM系统)(1)
查看>>
[luogu4310] 绝世好题 (递推)
查看>>
[luogu3203 HNOI2010] 弹飞绵羊 (分块)
查看>>
-Dmaven.multiModuleProjectDirectory system propery is not set.
查看>>
Python2 unichr() 函数
查看>>
Python 字典 copy()方法
查看>>
Minimum Path Sum
查看>>
Remove Duplicates from Sorted Array II
查看>>
常量指针和指针常量巧妙记忆方法[转]
查看>>
python-haproxy作业讲解视频总结
查看>>