关于andriod 数据库操作的优化

来源:互联网 发布:mysql distinct 编辑:程序博客网 时间:2024/05/18 03:46

转载地址:http://www.trinea.cn/android/database-performance/

1.创建索引

2.事物操作

Sqlite默认会为每个插入、更新操作创建一个事务,并且在每次插入、更新后立即提交。这样如果连续插入100次数据实际是创建事务->执行语句->提交这个过程被重复执行了100次。如果我们显示的创建事务->执行100条语句->提交会使得这个创建事务和提交这个过程只做一次,通过这种一次性事务可以使得性能大幅提升。尤其当数据库位于sd卡时,时间上能节省两个数量级左右。

public void insertWithOneTransaction() {    SQLiteDatabase db = sqliteOpenHelper.getWritableDatabase();    // Begins a transaction    db.beginTransaction();    try {        // your sqls        for (int i = 0; i < 100; i++) {            db.insert(yourTableName, null, value);        }        // marks the current transaction as successful        db.setTransactionSuccessful();    } catch (Exception e) {        // process it        e.printStackTrace();    } finally {        // end a transaction        db.endTransaction();    }}

3.sql语句的拼接 尽量用stringbuilder,简单的string 会额外的增加开销

4.精简查询语句,返回需要返回的字段.每个字段的查询都需要时间

5.游标获取列的索引, cursor.getColumnIndex(),可以在建表的时候用static变量记住某列的index,直接调用相应index而不是每次查询。

2
3
4
5
6
7
8
9
publicstaticfinalString      HTTP_RESPONSE_TABLE_ID                  =android.provider.BaseColumns._ID;
publicstaticfinalString      HTTP_RESPONSE_TABLE_RESPONSE            ="response";
publicstaticfinalint          HTTP_RESPONSE_TABLE_ID_INDEX            =0;
publicstaticfinalint          HTTP_RESPONSE_TABLE_URL_INDEX          =1; //
publicList<Object>getData(){
……
cursor.getString(HTTP_RESPONSE_TABLE_RESPONSE_INDEX);
……
}

6 单线程池的 异步操作


Android中数据不多时表查询可能耗时不多,不会导致anr,不过大于100ms时同样会让用户感觉到延时和卡顿,可以放在线程中运行,但sqlite在并发方面存在局限,多线程控制较麻烦,这时候可使用单线程池,在任务中执行db操作,通过handler返回结果和ui线程交互,既不会影响UI线程,同时也能防止并发带来的异常。

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();singleThreadExecutor.execute(new Runnable() { @Overridepublic void run() {// db operetions, u can use handler to send message afterdb.insert(yourTableName, null, value);handler.sendEmptyMessage(xx);}});

0 0