SQLite 速度惊人。包含 450 万条记录的测试表具有以下结构:
CREATE TABLE testtable (numericid INTEGER PRIMARY KEY, testtext TEXT);
它填充了 numericid (0, 1, .... ) 的递增值和 testtext 的字符串。
在 MacBook Pro(2009 年)上以原子方式完成所有插入需要 1 小时 42 分钟。生成的 SQLite 文件大小为 94 MB。
在 iOS 应用程序内部,数据库在 viewDidLoad 方法中打开。一个简单的按钮触发数据库查询,如下所示:
- (void)btnPressed:(UIButton *)sender{
NSLog(@"btn pressed, start");
sqlite3_stmt *statement = nil;
NSString *querystring;
querystring= [NSString stringWithFormat:@"SELECT * FROM testtable WHERE numericid = 2571312;"];
const char *sql = [querystring UTF8String];
NSLog(@"sql is: %s", sql);
if (sqlite3_prepare_v2(dbConnection, sql, -1, &statement, NULL)!=SQLITE_OK){
NSLog(@"sql problem occured with: %s", sql);
NSLog(@"%s", sqlite3_errmsg(dbConnection));
}
else
{
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *numericid = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
NSString *testtext = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
NSLog(@"%@",[NSString stringWithFormat:@"%@ (%@)", numericid, testtext]);
} // while
}
sqlite3_finalize(statement);
NSLog(@"btn pressed, finished");
}
导致输出:
2012-08-10 17:51:36.734 DBQueryTest[28462:707] Database Successfully Opened
2012-08-10 17:51:39.083 DBQueryTest[28462:707] btn pressed, start
2012-08-10 17:51:39.087 DBQueryTest[28462:707] sql is: SELECT * FROM testtable WHERE numericid = 2571312;
2012-08-10 17:51:39.099 DBQueryTest[28462:707] text2571312 (2571312)
2012-08-10 17:51:39.102 DBQueryTest[28462:707] btn pressed, finished
所以一个查询需要不到19 毫秒!这可以针对 numericid 的几个值重现,尽管我没有运行完全随机的统计评估测试。
结论:此测试设置满足您的要求。SQLite 绝对是一种方法。
更新:
具有 100000 个键值的快速随机访问测试验证了第一个结果。将 sql 语句字符串创建和耗时的 NSLog 输出排除在时间测量之外,平均数据库查询时间下降了一个数量级:
平均查询时间:1.8 ms
平均偏差:0.4 ms
最大查询时间:25.9 ms
最小查询时间:0.6 ms