内存空间Zone的挖掘

NSZone 是苹果对内存分配和释放的优化方式。NSZone不是一个对象;它是一个难懂的C结构,它被用于纪录关于内存处理(管理)一系列对象的信息。你几乎不需要担忧你自己的应用(applications)是怎样管理你自己的空间(zones)的 ;Cocoa透明地管理它。默认的NSZone在程序启动和所有对象被分配时创建。

所以你为什么想要去用你自己的NSZone呢?

如果你大量分配数百个小对象,事实上你会发现你花费精力来为他们分配内存是有意义的。因为这种标准的(默认的)空间会被一直使用,它会变得斑驳起来;释放对象的过程会给整个内存留下令人尴尬的空隙。标准空间的分配器(allocator)也知道知道这一点,所以它尝试着优先去使用被用户释放的内存,去填补这些空隙,但是这种方式只有在空间(zone) 变得很大时才有明显效果。

如果你想为大量对象分配内存,然后,你可以创建你自己的空间(zone)并且告诉它不用去为了为新对象分配内存而去查找那些空隙。分配器现在能够每次跳到内存分配的末尾为你的新对象分配内存,能起到不错的效果。

另外,分配器也能为你节省时间,当分配器向操作系统请求更多内存时,分配器去查找哪块空间什么时候被填满,需要花费不少时间。一种更快的时间是一次去请求一大块内存,你也能告诉你的NSZone在这儿做什么。

NSZone也能节省你释放内存的时间。它有方法释放大量分配的内存,而不打扰释放器(deallocators)。如果用一个集合(set)包含一系列对象,这样能够节省时间,你可以一次释放它们而不用去乏味地一个个释放它们。

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>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 style=”font-weight:bold”>NSZone method (NSRecycleZone) carefully puts all the objects in a zone neatly style=”font-weight:bold”>NSZone. Not exactly a huge time-saver.

So, in summary, zones save you time in mass allocations.