调用函数时,Android SQLite Cursor变慢

时间:2015-01-06 15:17:08

标签: java android sqlite android-asynctask

我在MotoG 2nd Gen (1GB RAM, Quad-core 1.2 GHz)测试了我的应用。我在类Misc中有以下静态方法。 itemRates数组是Object数组,长度为:132,包含大约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秒才能完成......嗯?!对于一个小阵列而言相当大。为了检查它是否是函数调用,我删除了函数调用,以便在大约1秒内找到AsyncTask完成!需要注意的是,我在swing应用程序中使用了相同的代码行,这也是一个Java框架。那么为什么在android中执行会花费这么多时间呢?知道如何解决这个困境吗?

1 个答案:

答案 0 :(得分:0)

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