android cursor movetofirst performance issue

2019-05-13 05:13发布

问题:

i am trying to optimize my application. I noticed that cursor.movetofirst() method somehow slowing the performance of my code.

Cursor cursor = myDbHelper.getDayInfo(new SimpleDateFormat("yyyy-MM-dd").format(myCalendar.getTime());

above line executes in 10 ms in 2.1 emulator, and

if(cursor != null && cursor.moveToFirst()) 

this line took about 1.6 seconds. I made little search about this. Somepeople say make it in another thread or in asynctask, but this will make the code more complicated. I 'm just trying to figure out what is actually happening to this cursor. Can anyone simplify or give a hint about database performance increase related to my question?

回答1:

It is natural, that moveToFirst() method gets much more time that other code. The data enquariyng actually takes place, which invokes database communication, data reading and so on. You actually can't do anything with it. The advice was right - move all the long operations to AsyncTask.



回答2:

It's been a while since this was marked answered but you never really got a great answer here. Even on a very large table a single row query should usually take much less than 1.6 seconds. The reason it's slow is that you don't have an index for the column(s) that you are querying on so it has to scan the entire table to find those values. If you create an index you can cut the time down to a fraction of a second.



回答3:

If the dataset held by the cursor is large, moving the cursor around takes time. You have to perform such data-intensive operations on a separate thread. Using an AsyncTask might make your code a tiny bit complex but it's worth it. This against the user thread being blocked at the cost of a broken UI experience.