我有很多对象,每个对象都有一些标签,这些标签存储在 NSDictionary 中。我还有一个循环,在其中我遍历所有对象并根据对象的标签做一些事情。方法 objectForKey:如果调用太多,性能会大大降低。我怎样才能提高性能?例如,我尝试在@property 中设置“strong”而不是“copy”,但这并没有解决问题。谢谢!
编辑:
这是某种代码,当然,它比我项目中的代码简单得多。Profiler 说热点在 objectForKey: 中,而不是在 doSomeStuff: 中。可能是因为它的电话数量吗?标签的对象很少,每个对象大约10个,但是对象的数量相当大
。H:
@interface MyObject : NSObject
@property (nonatomic, readwrite, strong/*copy*/ ) NSDictionary *tags;
-(void)doSomeStuff;
@end
米:
@implementation MyObject
{
NSDictionary *tags; // about 10 values for each object
}
-(NSDictionary *)tags
{
return tags;
}
-(void)setTags:(NSDictionary *)newTags
{
tags = [newTags copy];
}
-(void)doSomeStuff;
@end
使用:
NSArray *objects = ... // a lot of items, > 1000
NSArray *rules = ... // NSArray of objects with property NSArray* Strings, about 50 strings
for (MyObject *object in objects)
{
for (NSArray *rule in rules)
{
for (NSString *ruleString in rule.Strings)
{
// there is a more complicated check in my project, so you may imagine that there are 10 calls of objectForKey:, with different keys
if ([object objectForKey:ruleString] isEqualToString:@"yes"])
{
[object doSomeStuff];
}
}
}
}