Why is NSString autorelease in every for loop without @autoreleasepool

This is my test code:

for (int i = 0; i < 1000000000; ++i) {
    NSString *string = @"Abc";
    string = [string lowercaseString];
    string = [string stringByAppendingString:@"xyz"];
}

In an ARC environment, a loop will not explode. In my case, it just costs 1.2 MB of RAM to run this cycle.

But in MRC, the loop will cause the memory to explode, except for using the @autoreleasepool code block. What scares me, there are many articles that say you need to put codes in @autoreleasepool when the codes are in for a loop. but in this case, it doesn’t matter without @ autoreleasepool. Please help me with this. thanks.

update: if I write the code as follows:

for (int i = 0; i < 1000000000; ++i) {
    NSString *string = [NSString stringWithFormat:@"aaaaaaaaaaaaaaaaaaa"];
}

the code will cause the memory to explode in both ARC and MRC. why?

stringWithFormat:

also returns an autodetection object. I am puzzled by this ...

+4
source share
3

, ARC, , ARC. , , , , NSString, , ARC.

NSString , ARC, , ARC. , , , ARC.

, NSString ARC, objc_autoreleaseReturnValue() . ARC, ( , , ), objc_retainAutoreleasedReturnValue(). . objc_autoreleaseReturnValue() , objc_retainAutoreleasedReturnValue() , , objc_retainAutoreleasedReturnValue(), .

, , , , "" , , . .

ARC .

- @autoreleasepool , - . :

for (int i = 0; i < 1000000000; ++i) @autoreleasepool {
    NSString *string = @"Abc";
    string = [string lowercaseString];
    string = [string stringByAppendingString:@"xyz"];
}
+3

, ARC . . , .

- , . , .

, , . @autoreleasepool, , .

for (int i = 0; i < 1000000000; ++i) {
    @autoreleasepool {
        NSString *string = [NSString stringWithFormat:@"aaaaaaaaaaaaaaaaaaa"];
    }
}

: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html

+1

ARC .

ARC , lowercaseString, / , . ARC : lowercaseString , , , . /autorelease/, lowercaseString /, . ( , , ), .

, , , , .

0

Source: https://habr.com/ru/post/1615339/


All Articles