iOS 性能优化Tips

iOS 性能优化Tips

本文记录下在app调优过程中遇到的性能问题以及解决办法。(不定期更新)

1.NSDateFormatter耗时

老生常谈的问题,刚进入这个项目就发现代码大量使用了NSDateFormatter。自己新建了一个工程进行了测试,分别用了三种方法来进行NSDate和字符串的相互转换,其中:
Test1,采用标准的NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];随用随创建方式(显然不是Apple官方推荐的,也是我们代码中应该避免的)。
Test2采用static NSDateFormatter *dateFormatter;方式,静态化需要的变量,保证只创建一次。
Test3利用strptime函数来进行转换。
对此分别进行100次循环,查看运行耗时如下: 计算结果

结论:数据量大的时候还是少用NSDateFormatter吧!附Test3的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
+ (NSDate *)dateFromISO8601StringDateFormatter:(NSString *)string locale:(NSLocale *)locale{
if (!string) {
return nil;
}
struct tm tm;
time_t t;
strptime([string cStringUsingEncoding:NSUTF8StringEncoding], "%Y-%m-%d %H:%M:%S", &tm);
tm.tm_isdst = -1;
t = mktime(&tm);
return [NSDate dateWithTimeIntervalSince1970:t + [[NSTimeZone localTimeZone] secondsFromGMT]];
}
- (NSString *)ISO8601String:(NSDate*)date {
struct tm *timeinfo;
char buffer[80];
time_t rawtime = [date timeIntervalSince1970] - [[NSTimeZone localTimeZone] secondsFromGMT];
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
}

2.SQL操作耗时

拿查询举例,除了百度出来的那些SQL语句查询技巧外,由于我们的业务关系,在查询时加了锁,所以我们尽量减少了执行查询语句的次数,例如尽量避免如下这种操作

1
2
3
for(int i = 0; i < 100; i++){
[SQL search:"xxx = i"];
}

而是转化成下面的实现。

1
2
3
4
5
NSString *searchKey = @"";
for(int i = 0; i < 100; i++){
searchKey = [NSString stringWithFormat@""];
}
[SQL search:searchKey];

3.截屏动画操作耗时

开发中的动画很多是截取屏幕生成 UIImage来完成的。iOS7以后 UIView 类提供了一个方法-drawViewHierarchyInRect:afterScreenUpdates:,能够完整的把 view 的继承关系一并渲染 到 bitmap image。其实我们做动画只需要UIView就够了,完全不必渲染到 bitmap 后再操作,有没有更高效的方式呢? 有的,苹果 daddy 已经为我们准备了另外两个方法 UIView -snapshotViewAfterScreenUpdates: and -resizableSnapshotViewFromRect:afterScreenUpdates:withCapInsets:,这两个方法返回的是 UIView 对象,直接可以通过操作view 对象来执行动画,经过 instruments 测试,耗时由之前的200ms 缩短至4ms(由于 view 的继承关系不同,耗时会有变化,但是越复杂的 View 耗时越多)。相关文档链接

显示评论