1

我希望应用程序向 UserDictionary 添加几个 (2k) 单词。

我已经尝试过 ContentResolver().insert/bulk insert....

// array of words
    String[] words = getResources().getStringArray(R.array.word_array); 

    Long start,end = null;

    start = System.currentTimeMillis();


    int len = words.length;
    ContentValues[] mValueArray = new ContentValues[len];
    ContentValues mNewValues = new ContentValues();

    mNewValues.put(UserDictionary.Words.APP_ID, "com.my.example");
    mNewValues.put(UserDictionary.Words.LOCALE, "en");
    mNewValues.put(UserDictionary.Words.FREQUENCY, "100");

    for (int i = 0; i < len; ++i) {

        mNewValues.put(UserDictionary.Words.WORD, words[i]);

        mValueArray[i] = mNewValues;
    }

    getContentResolver().bulkInsert(
            UserDictionary.Words.CONTENT_URI,   // the user dictionary content URI
           mValueArray                       // the values to insert
        );
   end = System.currentTimeMillis();

   Toast toast = Toast.makeText(this, "Time for " + Integer.toString(len-1)+" words: " + Long.toString((end-start)) + "ms", 50);
   toast.show();

如果我批量插入 100 个单词,在我的手机上每个单词大约需要 100 毫秒。插入 2k 个单词需要 3 多分钟。

有人知道插入单词的更快方法或可以进行的任何优化吗?

附带问题:UserDictionary 大小有上限还是取决于手机?

任何帮助表示赞赏

迈克尔斯特

4

2 回答 2

2

Specific to your case: Adding 2000 words in the dictionary at a stretch will take time and there is not much of an optimization which can be done. The time you see here are for the file operation and moving from Java->NDK->Native operation.

General: Irrespective of the method used, one has to understand that these are nothing but file operations and is bound to take time. The APIs (including SQLite related) are just a wrapper to the intended file operations in the native code. Natively file write will always take a longer time then file read.

于 2012-02-15T17:15:56.717 回答
1

我在 Android 的源代码中看到,对于大型 sql 查询,使用了 applyBatch 方法。在 ContactsRemover 等其他一些程序中,作者也使用这种方法。但我不知道它是否真的比 insert 或 bultInsert 更快。

于 2012-02-15T17:04:03.407 回答