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也給出了對于事務處理的標準調用方式:
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
轉載于:https://www.cnblogs.com/raywalker/archive/2011/09/18/SQLite_insertion_optimization.html
總結
以上是生活随笔為你收集整理的SQLite中利用事务处理优化DB操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用Frame Animation实现动
- 下一篇: Log4j 入门总结