我正在尝试像这样优化返回 NSMutableDictionary 的函数:
-(NSMutableDictionary *)getValuses{
NSNumber *n1 = [NSNumber numberWithInt:-1];
NSNumber *n2 = [NSNumber numberWithInt:-1];
NSNumber *n3 = [NSNumber numberWithInt:-1];
NSNumber *n4 = [NSNumber numberWithInt:-1];
NSNumber *n5 = [NSNumber numberWithInt:-1];
if (self.k1)
n1 = self.k1;
if (self.k2)
n2 = self.k2;
if (self.k3)
n3 = self.k3;
if (self.k4)
n4 = self.k4;
if (self.k5)
n5 = self.k5;
NSMutableDictionary * dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:n1,[NSNumber numberWithInt:2],n2,[NSNumber numberWithInt:3],n3,[NSNumber numberWithInt:4],n4,[NSNumber numberWithInt:5],n5,[NSNumber numberWithInt:6], nil];
return dictionary;
}
我在循环中运行这个函数超过 100 万次,所以任何优化都是好的。它可以工作,但我希望它工作得更快。
最佳答案
你真的需要 -1 值的字典吗? 你可以避免所有“if/then”的东西(我听说它对于 cpu 来说可能很慢)如果你只是这样做
NSMutableDictionary * dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:k1,[NSNumber numberWithInt:2],k2,[NSNumber numberWithInt:3],k3,[NSNumber numberWithInt:4],k4,[NSNumber numberWithInt:5],k5,[NSNumber numberWithInt:6], nil];
// then you can do things like this
id obj = [dictionary objectForKey:@2];
if (obj)
NSLog(@"dict with good values");
else
NSLog(@"old dict with -1");
关于ios - 通过创建 NSDictionary 优化功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19583411/