gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:09:50 26 4
gpt4 key购买 nike

像这样的函数有很多

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com