25

Is SQLite cursor.getCount() expensive operation when executed on Android device?

Which is faster:

Cursor cursor = db.rawQuery(sql, null);
int length = cursor.getCount();
final List<Item> items = new ArrayList<Item>(length * 2); // need maybe 2 items per row

if (cursor.moveToFirst()) {

      // loop trough the query result
      do {
...

or

Cursor cursor = db.rawQuery(sql, null);
final List<Item> items = new ArrayList<Item>();  // capacity is 0 by default on android

if (cursor.moveToFirst()) {

      // loop trough the query result
      do {
peceps
  • 17,370
  • 11
  • 72
  • 79
  • I don't think there's significant difference in performance, unless you're talking considerable amount/size of elements. Otherwise, I think your question offers some subject to discuss as: is it better to allocated memory in advance on your phone to gain performance... – hovanessyan Dec 23 '11 at 16:49
  • 1
    I don't think there's ever a difference in performance. `cursor.moveToFirst()` calls `onMove` which calls `getCount`. So getCount can be very slow, but you can't really escape it. – Malabarba Aug 29 '13 at 09:21

1 Answers1

18

If you compare the time required for both code samples to execute, you'll notice it's the same because Cursor.moveToFirst() is eventually calling SQLiteCursor.getCount()

a.ch.
  • 8,285
  • 5
  • 40
  • 53