关于andriod 数据库操作的优化

转载地址: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
public static final String        HTTP_RESPONSE_TABLE_ID                    = android . provider . BaseColumns . _ID ;
public static final String        HTTP_RESPONSE_TABLE_RESPONSE              = "response" ;
public static final int            HTTP_RESPONSE_TABLE_ID_INDEX              = 0 ;
public static final int            HTTP_RESPONSE_TABLE_URL_INDEX            = 1 ; //
public List <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() {
 
	@Override
	public void run() {
		// db operetions, u can use handler to send message after
		db.insert(yourTableName, null, value);
		handler.sendEmptyMessage(xx);
	}
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值