发现一个有意思的测试结果。
@autoreleasepool 放在for 循环外面,即所有循环结束后才释放里面的延迟对象;而放在里面的话,也就是说每次循环都立即释放。
这样就保证了for循环时不会突然内存爆表。
但是,性能居然。。。。是放在里面的好点,附上代码,可以亲测玩玩。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"start"); CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); [self test1]; NSLog(@"外 %f", CFAbsoluteTimeGetCurrent() - start); start = CFAbsoluteTimeGetCurrent(); [self test2]; NSLog(@"内 %f", CFAbsoluteTimeGetCurrent() - start); NSLog(@"over"); } - (void)test2 { for (long i = 0; i < largeNumber; ++i) { @autoreleasepool { NSString *str = [NSString stringWithFormat:@"hello - %ld", i]; str = [str uppercaseString]; str = [str stringByAppendingString:@" - world"]; } } } - (void)test1 { @autoreleasepool { for (long i = 0; i < largeNumber; ++i) { NSString *str = [NSString stringWithFormat:@"hello - %ld", i]; str = [str uppercaseString]; str = [str stringByAppendingString:@" - world"]; } } }
时间: 2024-10-02 05:55:00