transaction除了保证完整性还能加速

来源:互联网 发布:三拼音域名 编辑:程序博客网 时间:2024/04/29 23:37
As described in my previous notes, SQLite, by default, creates a journal file for each transaction, and delete the file after the transaction completes. The above code does not explicitly create any transactions, so each insert call will be treated as an independent one. As a result, expansive file operations will be called frequently and slow down the process...

Therefore, I modified the code to make all the insert calls in the same batch in a single transaction:
try{  db.beginTransaction();  for each record in the list {     do_some_processing();     if (line represent a valid  entry) {        db.insert(SOME_TABLE, null, SOME_VALUE);     }     some_other_processing();  }  db.setTransactionSuccessful();} catch (SQLException e) {} finally {  db.endTranscation();}


I then tested the code in the emulator running on my notebook. The original code inserts at a rate of around 10 records per second, while the version with transaction inserts at a rate of 30+ records per seconds. WOW, that's a sound improvement!