开发者

Speeding up database writes

I have a ListActivity that uses a CursorAdapter to display some data. This data is the result of a web service call.

I am getting the response from the web service call, using the org.json.* library to parse it, and then writing the results to the app's SQLite3 database. The ListActivity's Cursor is then re-queried and the data shows in the list.

My problem is the database writing is excessively slow. The only thing I can think to do is to not use a CursorAdapter and just hold this data in memory. I was hoping someone 开发者_JS百科had another suggestion to speed things up. Perhaps a bulk insert of some kind?

It should be noted that I'm using a ContentProvider to do my inserting. So I call getContentResolver().insert(...).

Here are some times from a test that retrieved in 56 rows of data over LAN and displayed them:

Time to response: 178ms

Time to parse json: 16ms

Time to write 56 rows to the database: 5714ms

I'd ultimately like the time for database writing to be under 1000ms for this amount of data.


I had the some problem once and found that calling beginTransaction() on your database first followed by executing your insert queries. Example code:

    public void insertClassBatch(ArrayList<Class> batch) throws Exception
{
    this.getWritableDatabase().beginTransaction();
    for (Class c : batch)
    {
        this.insertClassStatement.bindString(1, c.getClassName());
        this.insertClassStatement.bindString(2, c.getClassValue());
        this.insertClassStatement.executeInsert();
    }
    this.getWritableDatabase().setTransactionSuccessful();
    this.getWritableDatabase().endTransaction();
}

this reduced inserting 100 rows (the size of a batch in this situation) from about 30s to 300ms or so.


Do you make a round trip for every row you write to the database, or can you batch all of them into a single round trip? I'd bet that network latency is the culprit if you're not batching.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜