iOS开发性能最佳实践之——容易出现耗时阻塞的检查清单(持续更新)

剪贴板读取

1
2
3
4
5
6
7
8
9
10
11
12
13
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
if (pasteboard.string.length > 0) {//这个方法会阻塞线程
NSString *text = [pasteboard.string copy];
[pasteboard setValue:@"" forPasteboardType:UIPasteboardNameGeneral];
if (text == nil || [text isEqualToString:@""]) {
return ;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self processShareCode:text];
});
}
});

日期格式化

1
2
3
4
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"yyyy#MM#dd#HH:mm#ss"];
NSString *result = [formatter stringFromDate:date];

文件读取

我们通常会使用NSFileManager来读取文件,但是NSFileManager读取文件并不是性能最好的,推荐使用stat.h里的’int stat(const char , struct stat ) __DARWIN_INODE64(stat);’方法。

NSFileManager

1
2
3
4
5
6
7
8
9
10
11
12
mach_timebase_info_data_t info;
if (mach_timebase_info(&info) != KERN_SUCCESS) return -1.0;
__darwin_off_t fileSize1 = 0;
uint64_t start = mach_absolute_time();
for (NSInteger i = 0; i <= 10000; i++) {
NSDictionary<NSFileAttributeKey, id>* attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:imagePath error:nil];
fileSize1= [attributes fileSize];
}
uint64_t end = mach_absolute_time();
uint64_t elapsed = end - start;
uint64_t nanos1 = elapsed * info.numer / info.denom;
return (CGFloat)nanos / NSEC_PER_SEC;

stat

1
2
3
4
5
6
7
8
9
10
11
12
mach_timebase_info_data_t info;
if (mach_timebase_info(&info) != KERN_SUCCESS) return -1.0;
__darwin_off_t fileSize = 0;
uint64_t start = mach_absolute_time();
for (NSInteger i = 0; i <= 10000; i++) {
int rs = stat(filePath, &statBuf);
fileSize= statBuf.st_size;
}
uint64_t end = mach_absolute_time();
uint64_t elapsed = end - start;
uint64_t nanos1 = elapsed * info.numer / info.denom;
return (CGFloat)nanos / NSEC_PER_SEC;

在iPhone6S设备10000次循环的测试条件下,stat是性能是NSFileManager的4倍左右

Blacktea wechat
ex. subscribe to my blog by scanning my public wechat account
记录生活于感悟,您的支持将鼓励我继续创作!