处理自动释放池和线程
如果我创建一个带有回调的线程,例如......
NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
while(1) {
//Process Stuff
}
[pool release];
我假设任何自动释放的东西都不会真正被释放,因为池永远不会耗尽。 我可以将事情更改为这样:
while(1) {
NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
//Process Stuff
[pool release];
}
但是如此频繁地分配/删除似乎有点浪费。有没有办法可以留出一块内存并在内存满后释放池?
If I create a thread with a callback like..
NSAutoreleasePool* pool = [NSAutoreleasePool alloc] 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不用担心,因为Autorelease 很快。你的第二个选择很好。事实上,在 ARC 中,由于新的
@autoreleasepool { }
语法,除了这两个选项之外,很难做任何事情。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.如果您在循环的每次迭代中分配了大量的自动释放内存,那么为每次迭代创建并释放一个新的池是正确的做法,以防止内存堆积。
如果您没有生成太多自动释放的内存,那么它不会有什么好处,您只需要外部池。
如果您分配了足够的内存,使得单次迭代无关紧要,但完成时内存已经很多,那么您可以每 X 次迭代创建并释放池。
* 您需要确定什么对您自己来说重要。
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.
* You need to determine what significant is for yourself.