iphone - 什么是 NSZone?使用initWithZone :?有什么好处

标签 iphone objective-c

像这样的函数有很多

1. NSDefaultMallocZone()
2. NSCreateZone();
3. NSRecycleZone();
4. NSSetZoneName();
5. NSZoneMalloc();
and many more related to NSZone

NSZone 是什么意思,在哪里以及什么时候使用这些功能?
initWithZone: 的优点是什么?如何在我的 iphone 应用程序中使用?

最佳答案

NSZone is Apple's way of optimizing object allocation and freeing. NSZone is not an object; it is an opaque C-struct storing information about how memory should be handled for a set of objects.

One rarely needs to worry about handling your own zones in applications; Cocoa handles it transparently. A default NSZone is created on startup and all objects default to being allocated there. So why would you want to use your own?

If you are mass-allocating hundreds of cheap objects, you may find the cost of actually allocating space for them becomes significant. Because the standard zone is used all the time, it can become very patchy; deleted objects can leave awkward gaps throughout memory. The allocator for the standard NSZone knows this, and it tries to fill these gaps in preference to grabbing more memory off the system, but this can be costly in time if the zone has grown quite large.

If you want to mass-allocate objects, then, you can create your own zone and tell it not to bother with finding gaps to put new objects in. The allocator can now jump to the end of its allotted memory each time and quickly assign memory to your new objects, saving a lot of effort.

Allocators can save you time elsewhere, too, as asking the OS for more memory, which a zone needs to do whenever it fills up, is another costly operation if it's done a lot. Much quicker is to ask for huge chunks of memory at a time, and you can tell your NSZone what to do here as well.

Rumor has it that NSZone could save you deallocation time in the Good Old Days, too, with a method that simply chucks away all the allotted memory without bothering to call deallocators. If a set of objects is self-contained, this could save a lot of time, as you can chuck them all away at once without tediously deallocating them all. Alas, there appears to be no sign of this godsend in the current documentation; the single NSZone method (NSRecycleZone?) carefully puts all the objects in a zone neatly on the default NSZone. Not exactly a huge time-saver.

So, in summary, zones save you time in mass allocations. But only if programmers know how to use them!

来自 CocoaDev

关于iphone - 什么是 NSZone?使用initWithZone :?有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6097007/

相关文章:

iphone - iPhone 和 Objective-C 的共享/独占锁机制?

iphone - 调暗 iPhone 屏幕,但不要让它休眠

ios - 在 CoreData 的 fetchedObjects 中编辑多个对象

ios - 如何在移动过程中定义 CALayer 在 UIView 中的位置

html - 在 iOS 上显示 HTML 内容和 native 内容的最佳解决方案是什么?

iphone - 标签首先完全显示,而不是像我也想要的那样淡入

iphone - 尝试(&失败)从 iPhone 向 sqlite 中插入数据

iphone - 是否可以提交具有不同名称的相同应用程序?

ios - 如何将 NSMutableArray 添加为 NSMutableArray 的 objectAtIndex

iphone - iOS - 旋转后整个 View 向上移动