Search code examples
javaandroidsqlitearraylistdatabase-cursor

What is faster - a Cursor or ArrayList?


I have an SQLite database which I have to be constantly retrieving data from. Changes may be done to the data between each retrieval.

My goal is to maximize the app performance, so what is the fastest way to do this retrieving?

I can imagine 2:

  • constantly opening and closing new cursors

  • query all data at the beginning and store it in an ArrayList. When changing the data, change both SQLite DB and the ArrayList using indexOf.

---- EDITED ----

I need the data to create markers in a google's map.

I have considered using CursorLoader but as I don't need to interact whith other apps I don't want to use Content Providers.

Would creating a custom loader be a good idea?


Solution

  • In short, while it's not always that simple, the fastest way to do things is all at once.

    Constantly making calls to and from a database can really make your apps performance bottleneck, especially if it's to a server and not just your devices SQLite database.

    Depending on what you're doing with the data, you may be able to look into something like a CursorAdapter which handles the display of rows from the database, and each time you insert/update a row, the CursorAdapter will update the ListView accordingly. It also handles the opening/closing/moving to next of the Cursor, making it very readable and easy for developers to follow.

    Again, however, try to do things in as few calls as possible. If you stick to using an ArrayList:

    • Make one call in the beginning for all items.
    • Loop through that cursor and add items to an array list.
    • Use the array list as a cache. Sure, you could update the DB each time you update the list (which might be safest, IMO), or you can just loop through the list and insert/update/delete when the app closes. If you take that approach, make sure you do so in a method like onPause(), as it is one of the earliest methods in which an Activity can be killed.