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

在使用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.com/reference/android/content/SharedPreferences.Editor.html

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值