【问题标题】:Android SQLite Cursor slow when calling function调用函数时Android SQLite光标慢
【发布时间】:2015-01-06 15:17:08
【问题描述】:

我在MotoG 2nd Gen (1GB RAM, Quad-core 1.2 GHz) 中测试了我的应用程序。我在类Misc 中有以下静态方法。 itemRates 数组是一个长度为 132 的 Object 数组,包含长度约为 50 个字符的字符串:-

public static double getDCRate(String item){
    for(int i=0;i<itemRates.length;i++){
        String ar[] = (itemRates[i]+"").split("[;]");
        if(ar[0].equals(item)){
            return Double.parseDouble(ar[1]);
        }
    }
    return 0;
} 

现在,在我的AsyncTask 中,我调用了这个函数,如下所示:-

/* db initialized */
                Cursor c = db.rawQuery(sql, null);
                if (c.moveToFirst()) {
                    do {
/* ... */
                double totalCost = 0.0;
                double ntwt_double = c.getDouble(c.getColumnIndex("Ntwt"));

                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN1")))*(c.getDouble(c.getColumnIndex("DP1"))/100)*ntwt_double;
                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN2")))*(c.getDouble(c.getColumnIndex("DP2"))/100)*ntwt_double;
                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN3")))*(c.getDouble(c.getColumnIndex("DP3"))/100)*ntwt_double;
                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN4")))*(c.getDouble(c.getColumnIndex("DP4"))/100)*ntwt_double;
                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN5")))*(c.getDouble(c.getColumnIndex("DP5"))/100)*ntwt_double;
                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN6")))*(c.getDouble(c.getColumnIndex("DP6"))/100)*ntwt_double;
                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN7")))*(c.getDouble(c.getColumnIndex("DP7"))/100)*ntwt_double;
                totalCost += Misc.getDCRate(c.getString(c.getColumnIndex("DN8")))*(c.getDouble(c.getColumnIndex("DP8"))/100)*ntwt_double;

AsyncTask 大约需要 12 秒才能完成..嗯?!对于迭代一个小数组来说相当大。为了检查它是否是函数调用,我删除了函数调用以找到 AsyncTask 在大约 1 秒内完成!需要注意的是,我在我的 swing 应用程序中使用了相同的代码行,它也是一个 Java 框架。那么为什么在android中执行需要这么多时间呢?知道如何解决这个难题吗?

【问题讨论】:

  • 您尝试过分析吗?它会让您更好地了解时间都花在了哪里。
  • @matiash,感谢您的提示。看我的回答。你能想到为什么split在android中消耗了这么多时间和内存,但是在swing中它就很好了吗?

标签: java android sqlite android-asynctask


【解决方案1】:

感谢@matiash,我分析了该方法,发现split(..) 是罪魁祸首。不知道为什么,split,Patter.splitter.. 和其他方法占总计算时间的 52%。不过奇怪的是,在使用 split 的替代品后,AsyncTask 会在大约 2 秒内加载。

【讨论】:

  • 到目前为止,还没有看到 split() 出现这种情况,但有一次我遇到了与 format() 类似的问题。很高兴你设法解决了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 2018-09-13
相关资源
最近更新 更多