Search code examples
androidandroid-sqlitesqliteopenhelper

Are Sqlite Insert , Delete, Synchronous in android


In my android application , i am doing SQlite DB operations like insert, delete, update records. i want to know , if i do like below:

long t1 = System.currentTimeMillis();
for(i =0; i<N; i++)
{
  insertRecord();
}
long t2 = System.currentTimeMillis();

does t2-t1 will equal the time taken to insert N records in DB. I mean is the call to insert synchronous or asynchronous.


Solution

  • If you are inside a transaction, the data will be actually written and synchronized only when the transaction ends.

    If you are not using explicit transactions, everything happens inside the insert() call, and you will indeed measure what you want. However, such operations are run with an implicit transaction, which makes them rather slow (because the synchronization overhead is there for every command).

    When you're doing several related database operations, you should put all of them into a single transaction:

    long t1 = System.currentTimeMillis();
    
    db.beginTransaction();
    try {
        for(i =0; i<N; i++) {
            insertRecord();
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    
    long t2 = System.currentTimeMillis();