问题
I would like app to add several (2k) words to UserDictionary.
I have experimented with 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();
On my phone takes about 100ms per word if I do bulkinsert on batches of 100. 3+ minutes to insert 2k words.
Is anyone aware of a faster method to insert words or any optimization that can be done?
Side question: Is there an upper limit on UserDictionary size or does that depend on phone?
Any help appreciated
Michealster
回答1:
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.
回答2:
I've saw in the sources of Android that for large sql queries applyBatch method is used. In some other programs as ContactsRemover the authors also use this method. But I do not know if it is really faster then insert or bultInsert.
来源:https://stackoverflow.com/questions/9297572/fastest-method-to-insert-words-into-userdictionary