0

This code tells me the amount of memory I'm currently consuming:

-(u_int)memoryUsage {
    u_int result = 0;
    struct task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(),
                                   TASK_BASIC_INFO,
                                   (task_info_t)&info,
                                   &size);
    if( kerr == KERN_SUCCESS ) {
        result = (info.resident_size / 1024) / 1024;
    } else {
        NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
    }
    return result;
}

To test this, I wrote this:

NSLog(@"USAGE: %u mb",[self memoryUsage]);

NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < 1000000; ++i) {
   [array addObject:@"Hello!"];
}

NSLog(@"USAGE: %u mb",[self memoryUsage]);
[array removeAllObjects];

NSLog(@"USAGE: %u mb",[self memoryUsage]);

The output is:

5 mb
10 mb
10 mb

After making an array with 1000000 strings, memory was increased by 5 mb. But after cleaning it up, memory usage is not modified.

Why is that?

Saturn
  • 17,888
  • 49
  • 145
  • 271
  • That function does not show how much memory your app is using. It shows how much address space the kernel has made available for a certain portion of your app. The connection between that number and object allocations is highly specious, at best. – bbum Jun 23 '13 at 23:06

1 Answers1

7

In general, freeing memory allocations from your program doesn't return that memory to the operating system. The memory allocation system keeps the freed memory around for use in later allocations.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469