需求
獲取一批客戶數(shù)據(jù)的時(shí)候铜涉,需要先調(diào)用接口拿到客戶的基本信息,然后再調(diào)用一個(gè)接口來獲取客戶的其他信息遂唧,最后合并在一起來使用芙代。
優(yōu)化前
一般情況下數(shù)據(jù)量不大,所以沒有多想盖彭,簡單的for循環(huán)了下:
for (CustomerNode *custModel in custInfoColumnArray) {
//結(jié)果集
NSMutableArray *resultMutiArray = [resultArray mutableCopy];
for (NSDictionary *dict in resultMutiArray) {
NSString *custNum = [dict valueForKey:@"custNum"];
NSString *unVisitDay = [dict valueForKey:@"unVisitDay"];
NSString *returnDay = [dict valueForKey:@"returnDay"];
// 判斷custNum一致
if ([custModel.custNum isEqualToString:custNum]) {
custModel.unVisitDay = unVisitDay;
custModel.returnDay = returnDay;
[resultMutiArray removeObject:dict];
break;
}
}
}
有一天客戶反映列表打開巨慢链蕊,一查這個(gè)resultArray居然至少有5000條數(shù)據(jù)事甜,測了下需要4秒才能處理完,必須進(jìn)行優(yōu)化了滔韵。
優(yōu)化
顯然通過for循環(huán)來查找對(duì)象速度太慢,那還有什么好辦法呢掌实?
考慮了一下陪蜻,使用key-value結(jié)構(gòu)的的hash表查找機(jī)制,應(yīng)該是效率最高的贱鼻,改造一下:
// 創(chuàng)建一個(gè)key-value結(jié)構(gòu)數(shù)據(jù)宴卖,key為需要匹配的cusNum,值為對(duì)應(yīng)的完整對(duì)象
NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
for (NSDictionary *dic in resultArray) {
[resultDict setValue:dic forKey:[dic valueForKey:@"custNum"]];
}
for (CustomerNode *custModel in custInfoColumnArray) {
// 直接通過valueForKey匹配到需要修改的對(duì)象
NSDictionary *dict = [resultDict valueForKey:custModel.custNum];
NSString *unVisitDay = [dict valueForKey:@"unVisitDay"];
NSString *returnDay = [dict valueForKey:@"returnDay"];
custModel.unVisitDay = unVisitDay;
custModel.returnDay = returnDay;
}
不出所料邻悬,因?yàn)橥ㄟ^KVC方式匹配數(shù)據(jù)效率高到可以忽略症昏,一共只循環(huán)了2次,執(zhí)行時(shí)間幾乎變?yōu)榱怂查g父丰,完美肝谭!