Android SharedPreferences中的方法commit和apply的区别

本文对比了Android中SharedPreferences.Editor的apply()与commit()方法。apply()异步将数据写入内存再写入磁盘,效率更高;commit()同步写入磁盘,有返回值确认是否成功。推荐使用apply()以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

当我在写代码的时候AS有个提示:

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

 

大体的意思就是:

尽量使用apply(),因为是异步的,commit()是同步的持久化存储

 

代码示例:

 

public void updateSpAsync() {
    SharedPreferences mySharedPreferences = getSharedPreferences("sp", MODE_PRIVATE);
    SharedPreferences.Editor editor = mySharedPreferences.edit();
    editor.putString("id", "this");
    editor.putBoolean("isLogin", true);
    editor.apply();
}

public void updateSp() {
    SharedPreferences mySharedPreferences = getSharedPreferences("sp", MODE_PRIVATE);
    SharedPreferences.Editor editor = mySharedPreferences.edit();
    editor.putString("id", "this");
    editor.putBoolean("isLogin", true);
    boolean result = editor.commit();
}

总结:

1)效率上

   在效率上,apply的效率比commit的效率高,因为apply是异步的,先将数据写入内存,然后写入磁盘;而commit是直接写入磁盘,我们知道写入磁盘的效率是比较低的

2)返回值

commit的方法是有返回值的,判断写入是否成功,而apply是没有返回值的

3)使用场景

尽量使用apply,而commit主要用在确保提交成功才有后续操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值