【问题标题】:Optimizing the performance of mass inserts from file SQLite Android从文件 SQLite Android 优化批量插入的性能
【发布时间】:2014-09-12 19:43:46
【问题描述】:

我目前正在和朋友一起开发一款主要处理文字的游戏,所以 我有一个输入数据库的单词列表。计划是在安装过程中填充个人数据库(如每个人的手机上)。我在 StackOverflow 和 Google 上找到的所有优化都做了,但还是太长了,差不多 2 分钟左右,对于这么简单的游戏来说是无法接受的。

单词表本身包含大约 350000 个单词,因此我们创建了一个文件,其中包含 相同数量的插入(这是最好的方法吗?),即每个单词在文本文件中都有自己的行,并带有相应的插入。这是我目前拥有的:

public int initializeDatabase(Context context) throws IOException {

        int result = 0; //returns querys completed
        SQLiteDatabase db = this.getWritableDatabase();
        //Opening a file for reading
        InputStream insertStream = context.getResources().getAssets().open("allWords.txt");
        BufferedReader insertReader = new BufferedReader(new InputStreamReader(insertStream));

        //Iterating through lines
        String query = "INSERT INTO words(word,tezina) VALUES(?,?)";//? entered in code
        SQLiteStatement statement = db.compileStatement(query);
        db.beginTransaction();//otvaram transakciju
        while(insertReader.ready()){
                statement.clearBindings();
                String toExtract = insertReader.readLine();//uzimam upit
                String word = "";
                int tezina = (int)toExtract.charAt(toExtract.length() - 2);//extract word difficulty
                for(int i = toExtract.length() - 4; i > 0; i--){

                    if(toExtract.charAt(i) == '(') break;
                    else word += toExtract.charAt(i);
                }//extract word along with ' ', from back to save time
                String reverseWord = "";
                for(int j = word.length() - 1; j >= 0; j--){
                    reverseWord = reverseWord + word.charAt(j);
                }//reverse it
                statement.bindString(1, word);//bind parameters
                statement.bindLong(2, tezina);
                statement.execute();
                result++;
        }
        db.setTransactionSuccessful();
        db.endTransaction();//end of transaction
        insertReader.close();
        return result;//return queries completed

    }

350262 插入,逐行,大约需要 2 分钟。有没有更好的方法来完成这一切?

【问题讨论】:

  • 你有索引吗?
  • 不,我目前没有。

标签: android database sqlite optimization


【解决方案1】:

文本文件的解析效率相当低(使用String而不是StringBuilder;构造未使用的reverseWord)。

但是,移动设备并不快;您将永远无法毫不拖延地解析和插入 350,000 行。

您首先不应该在设备上构建数据库。 只需将完整的数据库文件发送到 assets 文件夹中,然后在安装后发送 copy it to your data directory

【讨论】:

  • 我会试试这个,如果成功,然后标记你的答案。
  • 我已经成功地完成了所有这些工作,并成功地创建了一个要发货的数据库。谢谢!
猜你喜欢
  • 2013-01-20
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
  • 2012-11-10
  • 2019-06-24
  • 2014-01-16
  • 1970-01-01
  • 2018-09-04
相关资源
最近更新 更多