SQLite中利用事务处理优化DB操作

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

for (int i = 0; i < headers.length; i++) {
// ...
dataBase.insert(tableName, fields);
}


考虑如何提升操作性能时,在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 something
db.setTransactionSuccessful();
}
finally {
db.endTransaction();
}


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

转载请注明出处  http://www.cnblogs.com/raywalker/archive/2011/09/18/SQLite_insertion_optimization.html

posted @ 2011-09-18 00:29  C_ray  阅读(741)  评论(0编辑  收藏  举报