FMDB性能提升

作者: zaijianbali | 来源:发表于2017-06-12 17:43 被阅读135次

使用FMDB的过程中,性能的提升算一个技术点。

使用cache

既然是性能我们首先想到的是缓存cache
缓存的话,可以针对表进行提前关联到db,这个没有什么好说的。
就是把表中所有的表,放到一个map或者数组array中,访问的时候,不需要再生成了。

SQL 语法优化

别忘了where

其次,我们针对所有的sql语句的访问,增加耗时打点。
场景如下:
数据库表中有200条数据is_read = 0 ,现在把所有的数据都调用setAllRead标记已读(is_read = 1)
标记后(count(is_read = 0) = 0),再调用setAllRead 时间竟然不变。

从理论角度讲,这个时间应该变小,之前的代码如下:

- (int)setAllRead {
    CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
    NSString *format = @"update %@ set is_read = 1";
    NSString *sql = [NSString stringWithFormat:format, self.realTable];
    int result = [self.db executeUpdate:sql];
    LogPerformance(startTime);
    return result;
}

我们发现:这句sql 语句update %@ set is_read = 1 无论在什么情况下都遍历了一遍数据库表修改该值。现在数据库表是200条,如果是10000条或者更多,这个耗时就更多。
我们要修改的值是那些is_read = 0 的值,如果10000条里有一条is_read = 0 的信息,那么操作的数据量只有1条,按照这个思路,修改代码如下:

- (int)setAllRead {
    CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
    NSString *format = @"update %@ set is_read = 1 where is_read = 0";
    NSString *sql = [NSString stringWithFormat:format, self.realTable];
    int result = [self.db executeUpdate:sql];
    LogPerformance(startTime);
    return result;
}

结果如下:
数据库总共200条消息,

用时 Has where no where
200条未读 2.26ms 2.13ms
0条未读 0.12ms 2.34ms

也就是说提升20倍,1个数量级

所以 where 性能大法好

select DISTINCT

我们都知道,要查询数据库中枚举的值都有啥,比如查询数据库消息的类型,消息类型包括:文本、语音、图片......等等。
我可能会写成

NSString *format = @"select session_type from `%@` group by session_type";

其实这样写效率并不高,等于全量查完了,然后分类,我们不需要具体分类的值。

关键字DISTINCT 就起作用了。

代码简单修改:

  NSString *format = @"select DISTINCT session_type from `%@` ";

关键词 DISTINCT 用于返回唯一不同的值。

索引 index

其他

周末补上。。。。敬请期待

本文解释权归:子文

如需转载请注明出处,谢谢

来杯可乐催更吧

请子文喝可乐

相关文章

网友评论

    本文标题:FMDB性能提升

    本文链接:https://www.haomeiwen.com/subject/zoolqxtx.html