大量数据读写操作
@interface ViewController ()
@property (nonatomic, strong) NSMutableDictionary *msgCacheDict;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.msgCacheDict = [[NSMutableDictionary alloc] init];
[self.msgCacheDict setObject:@[].mutableCopy forKey:@"msgCacheDict"];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *array = @[@"1",@"2",@"3"];
for (NSInteger index = 0; index < 100000; index++) {
@autoreleasepool {
[self saveDataArray:array];
}
}
});
}
// 数组多次copy 操作,造成CPU占用很高,会引起卡顿
-(void)saveDataArray:(NSArray *)array {
// cpu占用率 85%
NSMutableArray *tempDataArray = [self.msgCacheDict objectForKey:@"msgCacheDict"];
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
if (tempDataArray.count > 0) {
[dataArray addObjectsFromArray:tempDataArray];
}
[dataArray insertObject:@"insert" atIndex:0]; // 添加新数据
[self.msgCacheDict setObject:dataArray forKey:@"msgCacheDict"];
NSLog(@"========save data1 ===");
}
// 数组不同方式初始化
-(void)saveDataArray2:(NSArray *)array {
// cpu占用率 90%
NSMutableArray *tempDataArray = [self.msgCacheDict objectForKey:@"msgCacheDict"];
NSMutableArray *dataArray = [[NSMutableArray alloc] initWithArray:tempDataArray];
[dataArray insertObject:@"insert" atIndex:0]; // 添加新数据
[self.msgCacheDict setObject:dataArray forKey:@"msgCacheDict"];
NSLog(@"========save data1 ===");
}
// 最佳方式 减少 copy操作
-(void)saveDataArray3:(NSArray *)array {
// cpu占用率 30% 但需要保证存储的是可变数组
NSMutableArray *dataArray = [self.msgCacheDict objectForKey:@"msgCacheDict"];
[dataArray insertObject:@"insert" atIndex:0]; // 添加新数据
NSLog(@"========save data 2 ===");
}
@end
总结
- 减少中间的冗余copy操作,节省CPU占用率
- 异步线程处理、否则卡主线程
网友评论