【问题标题】:Cursor in Android (SQLite)Android 中的光标 (SQLite)
【发布时间】:2012-04-30 12:32:32
【问题描述】:

Android 中的光标有问题...

public int getCountNameContainWord(String word){
    long time1=System.currentTimeMillis();
    Cursor cur = bdd.query(TABLE_IDF, new String[] {"COUNT(idfs)"}, "idfs LIKE '"+word+"%'", null, null, null, null, null);
    long time2=System.currentTimeMillis();
    System.out.println("time query : "+(time2-time1));
    if(cur!=null){
        cur.moveToFirst();
        long time3=System.currentTimeMillis();
        System.out.println("time move cursor : "+(time3-time2));
        int i=Integer.parseInt(cur.getString(0));
        return i;
    }else{
        return 0;
    }
}

结果:

时间查询:3

时间移动光标:3784

移动光标很慢,我不知道为什么...只有一个结果行... 你有想法让它更快吗?通常,它只需要几毫秒...

PS:对不起,我的英语不好,但我是法国人:/

【问题讨论】:

  • 我并不是说这就是答案,但我建议不要在计时操作时插入 I/O。 :-) 如果将所有 println() 语句移到 if..else 块之后,它是否会发生变化? (您还必须移动返回以进行测试。)

标签: android performance sqlite cursor


【解决方案1】:

编辑:
好的,我发现moveToFirst() 需要很长时间,因为它执行实际的数据库通信。您对此无能为力。如果它导致性能问题并阻塞您的 UI,您可以尝试将其移至 AsyncTask

android cursor movetofirst performance issue

你的桌子有多大?您可以尝试将索引添加到 idfs 并检查它是否有所作为。


我确定System.out.println 需要很多时间。所以试试这个:

public int getCountNameContainWord(String word){
    long time1 = System.currentTimeMillis();
    long time2, time3 = 0;
    Cursor cur = bdd.query(TABLE_IDF, new String[] {"COUNT(idfs)"}, "idfs LIKE '"+word+"%'", null, null, null, null, null);
    time2 = System.currentTimeMillis();
    if(cur!=null){
        cur.moveToFirst();
        time3 = System.currentTimeMillis();
        int i=Integer.parseInt(cur.getString(0));
        System.out.println("time query : "+(time2-time1));
        System.out.println("time move cursor : "+(time3-time2));
        return i;
    }else{
        return 0;
    }
}

【讨论】:

  • 同理:时间查询:4次移动光标:3652
【解决方案2】:

我认为答案就在这里Why Cursor Operation is taking so much time,我引用了

好的,伙计们,我已经有几天没来了。我找到了解决方案,即您必须为您的表创建索引,这将提高查询速度。

【讨论】:

  • 不,添加索引不会减少 moveToFirst() 所需的时间,它会减少查询时间本身
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 1970-01-01
  • 2011-12-17
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
相关资源
最近更新 更多