I was just wondering, why is there no autorelease pool optimization under the ARC compiler, where it would retain an object in the innermost scope, remove it from the autoreleas
Why do you believe that ARC doesn't optimize the above code? Try it in Release mode under Instruments. The heap doesn't grow. If you're testing under Debug, then the problem is that you're not engaging the optimizer.
You could probably break the functionality up into multiple calls which would give the code time to breath. Like having a method do x at a time, and when that method returned it would likely release that memory.
Any "remove from autorelease pool" operation would be inefficient. An autorelease pool is simply an array of pointers to release later. There's no fast way to check if a pointer is present in the pool.
ARC does have an optimization that can remove the autorelease from some cases where the callee performed return [obj autorelease]
. In my tests this reduces the autorelease pool overhead of -[NSNumber numberWithUnsignedInteger:] to zero.
It's possible that some versions of OS X or iOS implement -numberWithUnsignedInteger: in a way that prevents ARC's return-autorelease optimization. It's also possible that some compiler versions fail to perform the return-autorelease optimization when the returned object is unused.
In your original test, the internal implementation of NSLog() generated the autoreleased objects. There's nothing ARC can do about that short of wrapping every function call or every loop in an autorelease pool.