Android Sqlite Performance

前端 未结 3 1039
遇见更好的自我
遇见更好的自我 2020-12-05 01:33

I have been doing some experiments to measure sqlite performance on android. I was disappointed a little bit with the results. What i did was inserting 10.000 queries to ta

相关标签:
3条回答
  • 2020-12-05 01:47

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-05 01:54

    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. http://www.androidcode.ninja/android-sqlite-transaction-tutorial/

    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

    0 讨论(0)
  • 2020-12-05 02:02

    Well, you have so many records and for every record you call getWritableDatabase() and then insert it, which is bad for performance.

    You need to use transactions. Look at this question Android SQLite database: slow insertion. Basically you need to call beginTransaction(), do your insertions and then call setTransactionSuccessful() preceded by endTransaction(). You will be amazed to see how much performance gain you will get with this.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题