有助提升 SQLite 性能的最佳实践(视图)

概念和 Jetpack Compose 实现

SQLite 是一种高效的 SQL 数据库,Android 内置了对它的支持。遵循以下最佳实践可以优化您的应用的性能,确保随着数据的增多,您的应用仍能以可预测的速度快速运行。通过运用这些最佳实践,您还可以降低遇到难以重现且难以排查的性能问题的可能性。

要想实现更快的性能,请遵循以下性能原则:

  • 减少读取的行数和列数:优化您的查询,以便仅检索必要的数据。最大限度地减少从数据库读取的数据量,因为过多的数据检索可能会影响性能。

  • 将工作推送到 SQLite 引擎:在 SQL 查询中执行计算、过滤和排序操作。使用 SQLite 的查询引擎可以显著提升性能。

  • 修改数据库架构:设计数据库架构,帮助 SQLite 构建高效的查询计划和数据表示法。适当地为表添加索引并优化表结构,以便提升性能。

此外,您还可以使用可用的问题排查工具来衡量 SQLite 数据库的性能,以便确定需要优化的方面。

我们建议使用 Jetpack Room 库。

配置数据库以提升性能

通过框架或 Room 启用预写式日志记录 (WAL),而不是自行运行 PRAGMA journal_mode=WAL。在 Android 9(API 级别 28)及更高版本中,通过框架或 Room 启用 WAL 会打开一个连接池,并应用 WAL 同步模式(AOSP 中的 NORMAL),而无需手动配置。如需了解详情,请参阅启用预写式日志记录。

例如,在 SQLiteOpenHelper 子类的构造函数中启用 WAL,以便在数据库打开之前应用 WAL:

Kotlin

class AppDatabaseHelper(context: Context) :
    SQLiteOpenHelper(context, "app.db", null, DATABASE_VERSION) {

    init {
        setWriteAheadLoggingEnabled(true)
    }

    override fun onCreate(db: SQLiteDatabase) {
        // Create tables and indexes
    }

    override fun onUpgrade(
        db: SQLiteDatabase,
        oldVersion: Int,
        newVersion: Int
    ) {
        // Migrate the schema
    }
}

Java

public class AppDatabaseHelper extends SQLiteOpenHelper {
  public AppDatabaseHelper(Context context) {
    super(context, "app.db", null, DATABASE_VERSION);
    setWriteAheadLoggingEnabled(true);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    // Create tables and indexes
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Migrate the schema
  }
}

提高查询性能

遵循以下最佳实践可以最大限度地缩短响应时间、提高处理效率,从而提高 SQLite 中的查询性能。

只读取您需要的行

通过各种过滤条件,您可以指定日期范围、位置或名称等特定条件,从而缩小结果范围。通过各种限制,您可以控制系统显示的结果数量:

Kotlin

db.rawQuery("""
    SELECT name
    FROM Customers
    LIMIT 10;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        // Process cursor data
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT name
    FROM Customers
    LIMIT 10;
    """, null)) {
  while (cursor.moveToNext()) {
    // Process cursor data
  }
}

不要在 Kotlin 或 Java 代码中限制行数:

Kotlin

// Avoid: Cursor reads all matching rows before you break out of the loop.
db.rawQuery("""
    SELECT name
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    var count = 0
    while (count < 10 && cursor.moveToNext()) {
        // Process cursor data
        count++
    }
}

Java

// Avoid: Cursor reads all matching rows before you break out of the loop.
try (Cursor cursor = db.rawQuery("""
    SELECT name
    FROM Customers;
    """, null)) {
  for (int i = 0; i < 10 && cursor.moveToNext(); i++) {
    // Process cursor data
  }
}

即使循环在 10 行后停止,SQLiteCursor 也会延迟求值,并在首次移动时填充 CursorWindow,并且在 Android 17(API 级别 37)及更低版本中,还会统计 SQLite 中所有匹配的行。在 SQL 中添加 LIMIT,以便 SQLite 在生成这些行后停止扫描。

只读取您需要的列

避免选择不需要的列,否则可能会降低查询速度并浪费资源。请只选择所使用的列。

在以下示例中,您选择了 id、name 和 phone:

Kotlin

// Avoid: reads id and phone columns even though only name is used.
db.rawQuery(
    """
    SELECT id, name, phone
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        val name = cursor.getString(1)
        // Further processing
    }
}

Java

// Avoid: reads id and phone columns even though only name is used.
try (Cursor cursor = db.rawQuery("""
    SELECT id, name, phone
    FROM Customers;
    """, null)) {
  while (cursor.moveToNext()) {
    String name = cursor.getString(1);
    // Further processing
  }
}

但是,您只需要 name 列:

Kotlin

db.rawQuery("""
    SELECT name
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        val name = cursor.getString(0)
        // Further processing
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT name
    FROM Customers;
    """, null)) {
  while (cursor.moveToNext()) {
    String name = cursor.getString(0);
    // Further processing
  }
}

此外,请避免在生产查询中使用 SELECT *。

参数化查询

您的查询字符串可能包含仅在运行时已知的参数,例如:

Kotlin

// Avoid: string interpolation prevents statement reuse.
fun getNameById(id: Long): String? {
    db.rawQuery(
        "SELECT name FROM Customers WHERE id=$id", null
    ).use { cursor ->
        return if (cursor.moveToFirst()) {
            cursor.getString(0)
        } else {
            null
        }
    }
}

Java

// Avoid: string concatenation prevents statement reuse.
@Nullable
public String getNameById(long id) {
  try (Cursor cursor = db.rawQuery(
      "SELECT name FROM Customers WHERE id=" + id, null)) {
    if (cursor.moveToFirst()) {
      return cursor.getString(0);
    } else {
      return null;
    }
  }
}

而是将 id 实参替换为 ? 形参,并使用 selectionArgs 绑定值:

Kotlin

fun getNameById(id: Long): String? {
    db.rawQuery(
        """
          SELECT name
          FROM Customers
          WHERE id=?
        """.trimIndent(), arrayOf(id.toString())
    ).use { cursor ->
        return if (cursor.moveToFirst()) {
            cursor.getString(0)
        } else {
            null
        }
    }
}

Java

@Nullable
public String getNameById(long id) {
  try (Cursor cursor = db.rawQuery("""
          SELECT name
          FROM Customers
          WHERE id=?
      """, new String[] {String.valueOf(id)})) {
    if (cursor.moveToFirst()) {
      return cursor.getString(0);
    } else {
      return null;
    }
  }
}

文本查询、ContentResolver 查询和 Room 也是如此。Room @Query 方法会将 :arg 参数绑定为 ? 占位符,而使用串联 SQL 构建的 SimpleSQLiteQuery 实例会导致相同的问题:

Kotlin

// Avoid: evicts cached statements and introduces a SQL injection risk.
db.rawQuery("SELECT id FROM Customers WHERE city='$city'", null)
    .use { cursor ->
        // Process cursor data
    }

// Recommended: reuses one compiled statement safely.
db.rawQuery("SELECT id FROM Customers WHERE city=?", arrayOf(city))
    .use { cursor ->
        // Process cursor data
    }

Java

// Avoid: evicts cached statements and introduces a SQL injection risk.
try (Cursor cursor = db.rawQuery(
    "SELECT id FROM Customers WHERE city='" + city + "'", null)) {
  // Process cursor data
}

// Recommended: reuses one compiled statement safely.
try (Cursor cursor = db.rawQuery(
    "SELECT id FROM Customers WHERE city=?", new String[] {city})) {
  // Process cursor data
}

将运行时字面量串联到 SQL 中是 SQL 注入安全漏洞的常见来源。始终对未转义或未经验证的数据使用参数。即使您通过其他方式缓解了安全问题,在 SQL 中包含变量也会导致性能和诊断问题:

  • 语句缓存逐出:默认情况下,每个连接都会在最近最不常用 (LRU) 缓存中缓存 25 个预处理语句。每个唯一的 SQL 字符串都会导致缓存未命中,从而强制 SQLite 再次编译该语句,并从其他槽中逐出可重复使用的参数化语句。
  • Perfetto 和 dumpsys 中的非参数化字面量:Android 的 database Perfetto 跟踪和 dumpsys dbinfo 会省略绑定参数,仅记录 ? 占位符。Perfetto SQLite 切片或 dumpsys dbinfo -v 缓存转储中显示的任何字面量数字或字符串都来自应用代码中的非参数化 SQL。在 Android 16(API 级别 36)及更低版本中,每个不同的 SQL 字符串也会生成自己的异步轨迹。

对唯一值使用 DISTINCT

使用 DISTINCT 关键字可以减少需要处理的数据量,从而提高查询性能。例如,如果您只想返回某个列中的唯一值,请使用 DISTINCT:

Kotlin

db.rawQuery("""
    SELECT DISTINCT name
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        // Only iterate over distinct names in Kotlin
        // Process distinct name
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT DISTINCT name
    FROM Customers;
    """, null)) {
  while (cursor.moveToNext()) {
    // Only iterate over distinct names in Java
    // Process distinct name
  }
}

尽可能使用汇总函数

使用汇总函数可以获取不包含行数据的汇总结果。例如,以下代码会检查是否至少有一个匹配行:

Kotlin

// Avoid: fetches rows when you only need to test whether a match exists.
db.rawQuery("""
    SELECT id, name
    FROM Customers
    WHERE city = 'Paris';
    """.trimIndent(),
    null
).use { cursor ->
    if (cursor.moveToFirst()) {
        // At least one customer from Paris
    } else {
        // No customers from Paris
    }
}

Java

// Avoid: fetches rows when you only need to test whether a match exists.
try (Cursor cursor = db.rawQuery("""
    SELECT id, name
    FROM Customers
    WHERE city = 'Paris';
    """, null)) {
  if (cursor.moveToFirst()) {
    // At least one customer from Paris
  } else {
    // No customers from Paris
  }
}

若要仅检查是否存在匹配行,请使用 EXISTS(),以便在没有匹配行时返回 0,在有一行或多行匹配时返回 1:

Kotlin

db.rawQuery("""
    SELECT EXISTS (
        SELECT null
        FROM Customers
        WHERE city = 'Paris'
    );
    """.trimIndent(),
    null
).use { cursor ->
    if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
        // At least one customer from Paris
    } else {
        // No customers from Paris
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT EXISTS (
      SELECT null
      FROM Customers
      WHERE city = 'Paris'
    );
    """, null)) {
  if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
    // At least one customer from Paris
  } else {
    // No customers from Paris
  }
}

在应用代码中使用 SQLite 聚合函数:

  • COUNT:计算某个列中有多少行。
  • SUM:将某个列中的所有数值相加。
  • MIN 或 MAX:确定最小值或最大值。适用于数字列、DATE 类型和文本类型。
  • AVG:计算平均数值。
  • GROUP_CONCAT:使用可选分隔符来串联字符串。

使用 COUNT(),而不要使用 Cursor.getCount()

SQLiteCursor 会在您首次移动光标或调用 Cursor.getCount 时延迟评估查询。调用 getCount 会强制 SQLite 遍历每个匹配行(甚至超过前 CursorWindow 行)以计算总行数。如果您只需要计数,请使用 SQL 的 COUNT() 聚合函数:

Kotlin

// Avoid: forces SQLite to step through every row just to count them.
db.rawQuery("""
    SELECT id
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    val count = cursor.getCount()
    // Use count
}

Java

// Avoid: forces SQLite to step through every row just to count them.
try (Cursor cursor = db.rawQuery("""
    SELECT id
    FROM Customers;
    """, null)) {
  int count = cursor.getCount();
  // Use count
}

不过,通过使用 COUNT(),数据库只会返回计数:

Kotlin

db.rawQuery("""
    SELECT COUNT(*)
    FROM Customers;
    """.trimIndent(),
    null
).use { cursor ->
    cursor.moveToFirst()
    val count = cursor.getInt(0)
    // Use count
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT COUNT(*)
    FROM Customers;
    """, null)) {
  cursor.moveToFirst();
  int count = cursor.getInt(0);
  // Use count
}

在 Android 17(API 级别 37)及更低版本中,在 while (cursor.moveToNext()) 循环中迭代每一行之前调用 getCount 不会增加额外的工作,因为第一次移动无论如何都会计算计数。相比之下,调用 cursor.getCount() > 0 进行存在性检查或调用不带 LIMIT 1 的 moveToFirst 会触发完整扫描,而不是在找到第一个匹配项时停止,因此最好使用 SELECT EXISTS(...) 或 LIMIT 1。

嵌套查询,而非代码

SQL 是可组合函数,支持子查询、联接和外键约束条件。您可以在一个查询中使用另一个查询的结果,而无需使用应用代码。这样可以减少从 SQLite 复制数据的需要,并让数据库引擎优化您的查询。

在以下示例中,您可以运行查询来查找哪个城市的客户最多,然后在另一个查询中使用该结果来查找相应城市中的所有客户:

Kotlin

// This is not the most efficient way of doing this.
// See the following example for a better approach.

db.rawQuery("""
    SELECT city
    FROM Customers
    GROUP BY city
    ORDER BY COUNT(*) DESC
    LIMIT 1;
    """.trimIndent(),
    null
).use { cursor ->
    if (cursor.moveToFirst()) {
        val topCity = cursor.getString(0)
        db.rawQuery("""
            SELECT name, city
            FROM Customers
            WHERE city = ?;
        """.trimIndent(),
        arrayOf(topCity)).use { innerCursor ->
            while (innerCursor.moveToNext()) {
                // Process inner cursor data
            }
        }
    }
}

Java

// This is not the most efficient way of doing this.
// See the following example for a better approach.

try (Cursor cursor = db.rawQuery("""
    SELECT city
    FROM Customers
    GROUP BY city
    ORDER BY COUNT(*) DESC
    LIMIT 1;
    """, null)) {
  if (cursor.moveToFirst()) {
    String topCity = cursor.getString(0);
    try (Cursor innerCursor = db.rawQuery("""
        SELECT name, city
        FROM Customers
        WHERE city = ?;
        """, new String[] {topCity})) {
        while (innerCursor.moveToNext()) {
          // Process inner cursor data
        }
    }
  }
}

若要以上一个示例一半的时间获得结果,请使用带有嵌套语句的单个 SQL 查询:

Kotlin

db.rawQuery("""
    SELECT name, city
    FROM Customers
    WHERE city IN (
        SELECT city
        FROM Customers
        GROUP BY city
        ORDER BY COUNT(*) DESC
        LIMIT 1
    );
    """.trimIndent(),
    null
).use { cursor ->
    while (cursor.moveToNext()) {
        // Process cursor data
    }
}

Java

try (Cursor cursor = db.rawQuery("""
    SELECT name, city
    FROM Customers
    WHERE city IN (
      SELECT city
      FROM Customers
      GROUP BY city
      ORDER BY COUNT(*) DESC
      LIMIT 1
    );
    """, null)) {
  while(cursor.moveToNext()) {
    // Process cursor data
  }
}

在 SQL 中检查唯一性

如果不得插入某个行,除非某个列值在表中是唯一的,那么以列约束条件的形式强制执行该唯一性限制,可能会更高效。

在以下示例中,将运行一个查询来验证要插入的行,并执行另一个查询来插入该行:

Kotlin

// Avoid: runs two round trips instead of letting SQLite enforce uniqueness.
db.rawQuery(
    """
    SELECT EXISTS (
        SELECT null
        FROM Customers
        WHERE username = ?
    );
    """.trimIndent(),
    arrayOf(customer.username)
).use { cursor ->
    if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
        throw AddCustomerException(customer)
    }
}
db.execSQL(
    "INSERT INTO Customers VALUES (?, ?, ?)",
    arrayOf(
        customer.id.toString(),
        customer.name,
        customer.username
    )
)

Java

// Avoid: runs two round trips instead of letting SQLite enforce uniqueness.
try (Cursor cursor = db.rawQuery("""
    SELECT EXISTS (
      SELECT null
      FROM Customers
      WHERE username = ?
    );
    """, new String[] { customer.username })) {
  if (cursor.moveToFirst() && cursor.getInt(0) == 1) {
    throw new AddCustomerException(customer);
  }
}
db.execSQL(
    "INSERT INTO Customers VALUES (?, ?, ?)",
    new String[] {
      String.valueOf(customer.id),
      customer.name,
      customer.username,
    });

您可以在定义表时在 SQL 中检查唯一性约束条件,而不是在 Kotlin 或 Java 中检查:

CREATE TABLE Customers(
  id INTEGER PRIMARY KEY,
  name TEXT,
  username TEXT UNIQUE
);

SQLite 会执行与以下代码相同的操作:

CREATE TABLE Customers(...);
CREATE UNIQUE INDEX CustomersUsername ON Customers(username);

现在,您可以插入一行,并让 SQLite 来检查约束条件:

Kotlin

try {
    db.execSQL(
        "INSERT INTO Customers VALUES (?, ?, ?)",
        arrayOf(customer.id.toString(), customer.name, customer.username)
    )
} catch(e: SQLiteConstraintException) {
    throw AddCustomerException(customer, e)
}

Java

try {
  db.execSQL(
      "INSERT INTO Customers VALUES (?, ?, ?)",
      new String[] {
        String.valueOf(customer.id),
        customer.name,
        customer.username,
      });
} catch (SQLiteConstraintException e) {
  throw new AddCustomerException(customer, e);
}

SQLite 支持多列使用唯一索引:

CREATE TABLE table(...);
CREATE UNIQUE INDEX unique_table ON table(column1, column2, ...);

与 Kotlin 或 Java 代码相比,SQLite 能够更快地验证约束条件,并且开销更小。最佳实践是使用 SQLite,而非应用代码。

在单个事务中批量执行多个插入操作

在一个事务中提交多个操作,这不仅可以提高效率,还可以提高正确性。为了提高数据一致性和性能,您可以批量执行插入操作:

Kotlin

db.beginTransaction()
try {
    customers.forEach { customer ->
        db.execSQL(
            "INSERT INTO Customers VALUES (?, ?, ?)",
            arrayOf(customer.id.toString(), customer.name, "customerValue")
        )
    }
    db.setTransactionSuccessful()
} finally {
    db.endTransaction()
}

Java

db.beginTransaction();
try {
  for (Customer customer : customers) {
    db.execSQL(
        "INSERT INTO Customers VALUES (?, ?, ?)",
        new String[] {
          String.valueOf(customer.id),
          customer.name,
          "customerValue"
        });
  }
  db.setTransactionSuccessful();
} finally {
  db.endTransaction();
}

在显式事务之外,每个写入操作都在其自己的隐式事务中运行,并支付提交的全部费用,包括 FULL 同步模式下的 fsync。即使启用了 WAL 和 NORMAL 同步模式,未批处理的写入操作仍会按语句获取和释放写入锁、写入单独的 WAL 帧、触发定期检查点 fsync 调用,并在应用意外停止时留下部分更新。批处理只需支付一次提交费用,这可以使一批写入操作的速度提高一个数量级或更多。

请勿在事务中执行非数据库工作。请勿在阻塞文件 I/O(例如 File.delete)、网络请求、进程间通信(例如 ContentResolver 调用或广播)或锁获取期间保持打开的写入事务:

  • 并发数据库写入操作会阻塞,直到事务结束;如果没有 WAL,读取操作也会阻塞。
  • 如果在 beginTransaction 和 endTransaction 之间获取应用锁,则当另一个线程在等待数据库连接时持有该锁,可能会导致死锁。
  • 回滚失败的事务不会撤消外部副作用(例如已删除的文件),并且在 endTransaction 提交之前发送的广播会在您的更改可见之前唤醒接收器。

在调用 beginTransaction 之前准备外部输入,仅在 beginTransaction 和 endTransaction 之间运行 SQLite 操作,并在内存中记录所有文件路径或载荷,以便在 endTransaction 提交后运行清理或发送广播。

如果数据库引用不可变文件,请将这些文件存储在一个父级目录中,并在启动事务之前,以唯一名称创建、写入和同步每个文件。由于文件名是唯一的,并且数据库是活动文件的可信来源,因此请跳过原子重命名步骤。如需清理回滚事务或替换行留下的文件,请在对数据库写入和文件创建进行序列化的同一顺序写入执行器上(或在同一显式锁下)安排定期 WorkManager 作业,以便清理过程查询活动行并删除未引用的文件,而不会与正在进行的写入器发生冲突。