我正在尝试优化返回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;
}
我在循环中运行此函数超过1 000 000次,因此任何优化都是好的。它有效,但我希望它能更快地工作。
答案 0 :(得分:1)
-(NSMutableDictionary *)getValuses{
NSNumber *n1 = [NSNumber numberWithInt:-1];
NSMutableDictionary * dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:(self.k1)? self.k1:n1,[NSNumber numberWithInt:2],(self.k2)? self.k2:n1,[NSNumber numberWithInt:3],(self.k3)? self.k3:n1,[NSNumber numberWithInt:4],(self.k4)? self.k4:n1,[NSNumber numberWithInt:5],(self.k5)? self.k5:n1,[NSNumber numberWithInt:6], nil];
return dictionary;
}
尝试以上代码......
答案 1 :(得分:1)
你真的需要带有-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");
答案 2 :(得分:0)
您可以尝试这样的事情(未经测试):
-(NSMutableDictionary *)getValuses {
NSNumber *n = [NSNumber numberWithInt:-1];
NSMutableDictionary * dictionary =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
self.k1 ? self.k1 : n,[NSNumber numberWithInt:2],
self.k2 ? self.k2 : n,[NSNumber numberWithInt:3]...
return dictionary;
}
答案 3 :(得分:0)
您可以减少创建的NSNumber
个对象的数量,并且可以使用新的文字语法至少使代码更短和更短。更容易阅读。您还可以将属性访问次数减半。无论这些是否会对性能产生重大影响,您都必须找到答案。
-(NSMutableDictionary *)getValuses
{
NSNumber *n = @(-1);
return @{ @2: (self.k1 ?: n), @3: (self.k2 ?: n), @4: (self.k3 ?: n),
@5: (self.k4 ?: n), @6: (self.k5 ?: n)
};
}
(表达式a ?: b
是a ? a : b
的简写,但 a
只会被评估一次,因此属性访问次数减半。)< / p>
答案 4 :(得分:0)
试试这个! dispatch_appy方法用于创建循环并在并发队列中执行代码。这是执行大循环的更好方法。
dispatch_apply blocks - Apple Documentation
我没有编译它,但它应该工作。希望有助于给你一个线索。祝你好运!
-(NSMutableDictionary *)getValuses{
//add the values here
NSMutableArray *array = [@[self.k1,self.k2,self.k3,self.k4,self.k5]mutableCopy];
NSMutableDictionary * dictionary = [@{}mutableCopy];
//this kind of block is better for big loops...
size_t count = array.count;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(count, queue, ^(size_t i) {
id value = [array objectAtIndex:i];
[dictionary setObject:value?value:(@-1) forKey:@(i)];
});
return dictionary;
}