我需要解析一个相当大的XML文件(大小在100KB到几百KB之间),我使用的是Xml#parse(String, ContentHandler)
。我目前正在用一个152KB的文件来测试它。
在解析过程中,我还使用与下面类似的调用将数据插入到SQLite数据库中:getWritableDatabase().insert(TABLE_NAME, "_id", values)
。对于152KB的测试文件,所有这些加起来大约需要80秒(归结为插入大约200行)。
当我注释掉所有insert语句时(但保留所有其他语句,如创建ContentValues
等)同样的文件只需要23秒。
数据库操作有这么大的开销是正常的吗?对此我能做些什么吗?
发布于 2010-08-17 18:46:55
您应该进行批量插入。
伪码:
db.beginTransaction();
for (entry : listOfEntries) {
db.insert(entry);
}
db.setTransactionSuccessful();
db.endTransaction();
这极大地提高了在我的应用程序中插入的速度。
更新:
@Yuku提供了一篇非常有趣的博客文章:Android using inserthelper for faster insertions into sqlite database
发布于 2011-11-17 05:01:59
编译sql insert语句有助于提高速度。它也可能需要更多的努力来支撑一切并防止可能的注射,因为现在一切都在你的肩膀上。
另一种也可以提高速度的方法是文档不足的android.database.DatabaseUtils.InsertHelper类。我的理解是它实际上包装了编译后的insert语句。对于我的大型(200K+条目)但简单的SQLite插入,从非编译的事务插入到编译的事务插入的速度大约提高了3倍(每个插入2ms,每个插入的.6ms )。
示例代码:
SQLiteDatabse db = getWriteableDatabase();
//use the db you would normally use for db.insert, and the "table_name"
//is the same one you would use in db.insert()
InsertHelper iHelp = new InsertHelper(db, "table_name");
//Get the indices you need to bind data to
//Similar to Cursor.getColumnIndex("col_name");
int first_index = iHelp.getColumnIndex("first");
int last_index = iHelp.getColumnIndex("last");
try
{
db.beginTransaction();
for(int i=0 ; i<num_things ; ++i)
{
//need to tell the helper you are inserting (rather than replacing)
iHelp.prepareForInsert();
//do the equivalent of ContentValues.put("field","value") here
iHelp.bind(first_index, thing_1);
iHelp.bind(last_index, thing_2);
//the db.insert() equilvalent
iHelp.execute();
}
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
}
db.close();
发布于 2010-08-18 13:23:18
如果表上有索引,请考虑在插入记录之前删除它,然后在提交记录后再添加回来。
https://stackoverflow.com/questions/3501516
复制相似问题