Android Sqlite Performance

Use SQLite transaction for speed up

Use BEGIN TRANSACTION & END TRANSACTION for SQLite Optimization

Each SQL statement is enclosed in a new transaction block by SQLite runtime, by default. Sowhen you perform a basic DB operation such as INSERT, a transaction block will be created and wrapped around it.

Letting SQLite runtime manage the transaction for you is advisable only if your routine performs only one DB operation on a data set. However, if you are doing numerous DB operations (say INSERT inside for loop), this becomes very expensive, since it requires reopening, writing to, and closing the journal file for each statement.
You may refer

  1. Android SQLite database: slow insertion

  2. Android SQLite Transaction Example with INSERT Prepared Statement

  3. http://www.techrepublic.com/blog/software-engineer/turbocharge-your-sqlite-inserts-on-android/

  4. http://www.android-app-market.com/sqlite-optimization-in-android-programming-sqlite-optimization-in-android-apps.html

You can use SQL transactions in Android like this. It’s better to insert multiple rows into the database in larger batches then making single commit (write into SQLlite datafile which is very slow) for every inserted row.

public void insert(List<Student> students)
{
    SQLiteDatabase db = sh.getWritableDatabase();
    ContentValues cv = new ContentValues();

    db.beginTransaction();

    try {
        for (Student s : students) {
            cv.put(StudentHelper.FIRSTNAME,s.getFirstName());
            cv.put(StudentHelper.LASTNAME,s.getLastName());
            cv.put(StudentHelper.ADDRESS,s.getAddress());
            cv.put(StudentHelper.GPA,s.getGpa());

            db.insertOrThrow(StudentHelper.TABLE_NAME, null, cv)
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

Leave a Comment