SQLite查询需要太多的CPU

时间:2013-10-15 07:31:53

标签: ios performance sqlite

在我的应用程序中,我使用这两种方法:

- (NSString *)Method1:(NSString *)identificativo :(int)idUtente {
fileMgr = [NSFileManager defaultManager];
sqlite3_stmt *stmt=nil;
sqlite3 *dbase;
NSString *ora;
NSString *database = [self.GetDocumentDirectory stringByAppendingPathComponent:@"db.sqlite"];
sqlite3_open([database UTF8String], &dbase);
NSString *query = [NSString stringWithFormat:@"select MAX(orario) from orari where flag=0 and nome=\"%@\" and idutente=%d group by orario", identificativo, idUtente];
const char *sql = [query UTF8String];
sqlite3_prepare_v2(dbase, sql, -1, &stmt, NULL);
while(sqlite3_step(stmt) == SQLITE_ROW) {
    NSString *orario = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dataV = [formatter dateFromString:orario];
    ora = [formatter stringFromDate: dataV];
}
sqlite3_finalize(stmt);
sqlite3_close(dbase);
return ora;
}

第二个:

- (int)Method2:(NSString *)nomeM :(int)idUtente {
__block int conteggio = 0;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^(void) {
    fileMgr = [NSFileManager defaultManager];
    sqlite3_stmt *stmt=nil;
    sqlite3 *dbase;
    NSString *database = [self.GetDocumentDirectory stringByAppendingPathComponent:@"db.sqlite"];
    sqlite3_open([database UTF8String], &dbase);
    NSString *query = [NSString stringWithFormat:@"select nome, count(*) from orari where datetime(orario)>datetime('now','localtime') and flag=0 and nome=\"%@\" and idutente=%d group by nome", nomeM, idUtente];
    const char *sql = [query UTF8String];
    sqlite3_prepare_v2(dbase, sql, -1, &stmt, NULL);
    while(sqlite3_step(stmt) == SQLITE_ROW) {
    conteggio = [[NSNumber numberWithInt:(int)sqlite3_column_int(stmt, 1)] intValue];
    }
sqlite3_finalize(stmt);
sqlite3_close(dbase);
});
return conteggio;
}

这两种方法在执行时都会将模拟器CPU速度发送到100%并阻止UI。在第二个我尝试使用另一个线程,但它是相同的。 他们正在读取的表包含7000条记录,因此它可能取决于查询的不良优化,或者可能是其他内容。我没有任何线索。

任何帮助都会非常感激。

编辑:这是表架构:

dataid -> integer -> Primary key
orario -> datetime
nome -> varchar (150)
flag -> integer
pos -> varchar (150)
idutente -> integer

我应该在哪里使用索引?是什么类型的?

另一件事:现在正在观看表架构,我注意到有一个错误:列“nome”应该是一个varchar(实际上它包含一个字符串)但在我的架构中是整数类型。我不知道这是否与我的问题有关,整数列如何存储文本字符串...

1 个答案:

答案 0 :(得分:1)

这些行是个大问题:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

他们可以花费0.2秒以上。这是一个疯狂昂贵的电话。你真的只需要一次只设置一个NSDateFormatter并让它们全部使用它。要么在循环之外进行设置,要么更好,将其设置为静态并保持它以进行多次调用。

同样在这:

NSString *query = [NSString stringWithFormat:@"select nome, count(*) from orari where datetime(orario)>datetime('now','localtime') and flag=0 and nome=\"%@\" and idutente=%d group by nome", nomeM, idUtente];

如果您能够修改数据库,this solution可能会帮助您提高速度。

您正在为datetime('now', 'localtime')反复进行相同的计算。有更快的方法来存储和比较数据库中的时间。