java sqlite 事务处理_SQLite中利用事务处理优化DB操作

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 19:16   2215   0

前几天Android应用开发过程中碰到一个问题,当将大量数据插入到数据库(sqlite3)时,在Log中发现独立线程进行处理的约上百次insert操作竟然耗费了10.6s 的时间。

for(inti=0; i

}

考虑如何提升操作性能时,在SQLite的官方网站上的常用问答中找到了以下的信息:

By default, each INSERT statement is its own transaction. But if you surround multiple INSERT statements with BEGIN...COMMITthen all the inserts are grouped into a single transaction. The time needed to commit the transaction is amortized over all the enclosed insert statements and so the time per insert statement is greatly reduced.

就insertion操作自身来看,每一次的调用都会默认被当成一次事务(transaction)来进行处理,其中就包含了开启、提交、结束事务等基本元操作。代码中的大量插入数据操作,使得这些基本操作被重复执行了N次。大块的执行时间无疑会被白白耗费掉。同时注意到Android SDK文档的SQLiteDatabase也给出了对于事务处理的标准调用方式:

db.beginTransaction();try{//do somethingdb.setTransactionSuccessful();

}finally{

db.endTransaction();

}

OK, 贴图对比看下改进后同样的操作所耗费的时间吧 (debug下0.16s, 是的两者数量级相差有近百倍) ;)

8283267851ed9320d1220e41776e381d.png

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP