11. PHP Memory Management
It’s a good time to say few words about PHP Memory Manager.
The PHP Memory Manager API looks very much like classical libc malloc API, but it uses separate heap and it is especially optimized for PHP requirements. Usually, all the memory allocated during request processing should be freed at the end of a request at once. PHP allocator is especially optimized to do this extremely fast and without system memory fragmentation. It also avoids thread-safe checks, because even in multi-thread environment, each PHP thread is going to use a separate heap.
- emalloc(size_t size) – allocates the given amount of memory in the PHP request heap and returns pointer.
- safe_emalloc(size_t num, size_t size, size_t offset) – calculates the amount of required memory as (size * num + offset), checks for possible overflow, and allocates memory similar to emalloc().
- ecalloc(size_t num, size_t size, size_t offset) – allocates memory similar to safe_emalloc() and clears it (fill by zero byte).
- erealloc(void *ptr, size_t new_size) – reallocates a pointer, previously allocated in PHP request heap. This function may truncate or extend the allocated memory block, may move it into another memory location, or re-size in place. In case ptr is NULL, it’s equivalent to emalloc().
- efree(void *ptr) – frees the memory block previously allocated in PHP request heap.
The compete Zend Memory Manager API is defined in Zend/zend_alloc.h.