Java – Which is faster – Cursor or ArrayList?

Which is faster – Cursor or ArrayList?… here is a solution to the problem.

Which is faster – Cursor or ArrayList?

I have

a SQLite database from which I have to constantly retrieve data. Changes to the data may occur between each retrieval.

My goal is to maximize application performance, so what is the fastest retrieval method?

I can imagine 2:

  • New cursors are constantly opened and closed

  • Query all the data at the beginning and store it in an ArrayList. When changing data, use indexOf to change SQLite DB and ArrayList.

—- Edited —-

I need data to create markers on Google Maps.

I

considered using CursorLoader, but since I don’t need to interact with other apps, I don’t want to use a content provider.

Is it a good idea to create a custom loader?

Solution

In short, while things aren’t always that simple, the fastest way is to do everything at once.

Constantly making calls to and from the database can really make your application performance bottleneck, especially if it’s against the server and not just your device SQLite database.

Depending on how you handle the data, you might be able to look at CursorAdapter like of the content. It handles the display of rows in the database, and each time a row is inserted/updated, the CursorAdapter updates the ListView accordingly. It also handles opening/closing/moving to the next of the Cursor, making it very readable and easy for developers to follow.

However, try again to complete the task in as few calls as possible. If you stick with ArrayList:

  • One call for all projects at the beginning.
  • Iterates through the cursor and adds items to the array list.
  • Use an array list as a cache. Of course, you can update the database every time you update the list (which is probably the safest, IMO), or you can loop through the list and insert/update/delete when the application is closed. If you take this approach, make sure to do it using something like onPause(), as it is one of the earliest ways to terminate an activity.

Related Problems and Solutions