0

Is there any memory leak in below code? I guess NO, but for me below code allocates memory but not releasing it.

Any help is appreciated

@autoreleasepool {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (int i = 0; i < 300000; i++) {
        @autoreleasepool {
            [dict setObject:[NSNumber numberWithInt:i] forKey:[NSNumber numberWithInt:i]];
        }
    }
    [dict removeAllObjects];
}
Sebastian
  • 7,670
  • 5
  • 38
  • 50
user2317738
  • 281
  • 2
  • 10

1 Answers1

1

I don't know if this affects your issue, but it is worth knowing...

NSNumber does some fancy things behind the scenes, especially for the integers 0 - 12. It doesn't always release them, since it assumes that it is highly likely that it will need to reuse them in the future. They are considered to be used commonly enough to not want to retain / delete them all of the time.

See this discussion.

This might account for a little bit of memory not getting released, but it won't account for a huge amount.

It would be interesting to put your above code in a for loop, and see if calling it many times increases memory, or if the amount of memory used stays flat.

for (int i = 0; i < 100; i++) {
    @autoreleasepool {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        for (int i = 0; i < 300000; i++) {
            @autoreleasepool {
                [dict setObject:[NSNumber numberWithInt:i] forKey:[NSNumber numberWithInt:i]];
            }
        }
        [dict removeAllObjects];
    }
}

If it stays flat, I wouldn't worry too much about it.

Community
  • 1
  • 1
Skotch
  • 3,072
  • 2
  • 23
  • 43
  • I tried with suggested for loop, memory usage is same for both(with & without for loop) approximate 256 MB. 256 MB !, isn't it too much? I understand about 1 to 12, but it should release for others – user2317738 Apr 25 '13 at 16:26
  • You say you don't have a memory leak, but for some period of time you need a huge dictionary that increases your memory load. So that is your peak memory load and you may want rework your code to not require a 300K object dictionary. The fact that the memory does not go down after that may just be the OS keeping the memory assigned to your app in case you need it again. – Skotch Apr 25 '13 at 18:13
  • Is this iOS or OS X? If iOS, measure memory on the device, not the simulator. – Skotch Apr 25 '13 at 18:22
  • It is OS X, As you mentioned, the reason might be "The fact that the memory does not go down after that may just be the OS keeping the memory assigned to your app in case you need it again." – user2317738 Apr 25 '13 at 21:06
  • For what its worth: depending on your architecture, you can sometimes do things in a second temporary process. When the forked process goes away, so does all of its memory. – Skotch Apr 25 '13 at 21:10