I just finished implementing an autorelease pool opaque type for the MPRuntime, and to be honest, it’s pretty sweet. Basically an autorelease pool is a list that you put object pointers in, and then when you are done with the pool and you release it, it releases all of the objects in the pool. This can greatly reduce code size and also delay calling expensive memory free calls until a single moment.
Non-autorelease pool way:
Below is the old code for creating an array, and then adding 100 integers to it.
// Create an array and add a bunch of integers to it.
MPArrayRef array = MPArrayCreate(&kMPTypeArrayCallbacks);
for (unsigned i = 0; i < 100; i++)
{
MPNumberRef num = MPNumberCreateWithUnsigned(i);
MPArrayAppendValue(array, num);
MPRelease(num);
}
// Release our array.
MPRelease(array);
As you can see, it’s quite a hassle to keep the pointer around so you can call release on it. The example above isn’t the greatest because there are no like nested function calls and such, but just imagine magnifying the number of MPRelease statements and how many pointers you would have to keep around. So instead, as in the example below, you can simply autorelease the object so you don’t have to keep that pointer around, and you can send created objects directly in as arguments to function calls and what not.
Autorelease pool way:
// Create the pool.
MPAutoreleasePoolRef pool = MPAutoreleasePoolCreate(0);
// Create an array and add a bunch of integers to it.
MPArrayRef array = MPAutorelease(MPArrayCreate(&kMPTypeArrayCallbacks));
for (unsigned i = 0; i < 100; i++)
MPArrayAppendValue(array, MPAutorelease(MPNumberCreateWithUnsigned(i)));
// Release the pool, thus draining it.
MPRelease(pool);
Now that’s what I call sweet!
The files on the MPRuntime page contain the autorelease pool.
0 Responses to “MPRuntime now has autorelease”