开发者

Handling AutoRelease Pools and Threads

If I create a thread with a callback like..

NSAutoreleasePool* pool = [NSAutoreleasePool 开发者_如何学JAVAalloc] init];
while(1) {
   //Process Stuff
}
[pool release];

I assume that anything autoreleased will never really be freed since the pool is never drained. I could change things around to be like this:

while(1) {
   NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
   //Process Stuff
   [pool release];
}

But it seems a bit wasteful to alloc/delete so often. Is there a way I can set aside a block of memory and release the pool once its full?


Don't worry about it, because Autorelease is Fast. Your second option is fine. And in fact, in ARC, it will be hard to do anything besides those two options because of the new @autoreleasepool { } syntax.


If you allocate a significant* amount of autoreleased memory in each iteration of your loop, then creating and releasing a new pool for each iteration is the proper thing to do, to prevent the memory from piling up.

If you don't generate much autoreleased memory, then it wouldn't be beneficial and you will only need the outer pool.

If you allocate enough memory that a single iteration is insignificant, but there is a lot by the time you are done, then you could create and release the pool every X iterations.

#define IterationsPerPool 10
NSAutoreleasePool* pool = [NSAutoreleasePool new];
int x = 0;
while(1) {
   //Process Stuff
   if(++x == IterationsPerPool) {
      x = 0;
      [pool release];
      pool = [NSAutoreleasePool new];
   }
}
[pool release];

* You need to determine what significant is for yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜