网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

SharedPreferences.Editor的apply()与commit()方法的区别

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.


分享标题:SharedPreferences.Editor的apply()与commit()方法的区别
URL地址:http://bjjierui.cn/article/ppgehg.html

其他资讯