NSZone
is a type representing a memory allocation. NSObject
implements the allocWithZone:
method to allocate memory in a specific zone, or the default zone if none is provided; alloc
is equivalent to allocWithZone:nil
.
NSZone
was originally created to allow custom allocation and deallocation:
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.
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.
(source)
However, in modern programs, the zone is always nil
. From the archived Objective-C documentation:
- You cannot use memory zones.
There is no need to useNSZone
any more—they are ignored by the modern Objective-C runtime anyway.
Custom allocators have been used in other languages as well, such as by the C++ STL. Given the potential benefits to custom allocation, why was NSZone
deprecated? And why do (most) modern languages provide no equivalent?