Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack and heap in PHP?

I am learning about operating systems and the thing that I do not understand exactly are heaps and stacks. I know the benefits and how each works, but in the case of dynamic languages I can not figure out how is the stack allocated.

In static typed languages all primitive data types are stored on the stack since they are small and will be deallocated more or less in the same order they were allocated, however in languages like PHP this is not known until the run time. So how is the stack size and variable allocation possible?

If I understand correctly stack size is determined on compile time by analysing number of primitive data types and some offset. How is the process done in PHP or other dynamic languages?

If this question is kick in the dark, please give me some guides how to learn about this

like image 280
gorgi93 Avatar asked Jun 14 '14 19:06

gorgi93


People also ask

What is difference between stack and heap?

Stack space is mainly used for storing order of method execution and local variables. Stack always stored blocks in LIFO order whereas heap memory used dynamic allocation for allocating and deallocating memory blocks. Memory allocated to the heap lives until one of the following events occurs : Program terminated.

Is Ram a stack or heap?

Stack and a Heap ? Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.

Why stack is faster than heap?

Because the data is added and removed in a last-in-first-out manner, stack-based memory allocation is very simple and typically much faster than heap-based memory allocation (also known as dynamic memory allocation) e.g. C's malloc .


1 Answers

  1. If I understand it correctly, all PHP data types are zval. And zval is basing on a few "Z" data type (defined in C). There are limit number of "real" data type. I believe they are stored in the stack.

    So although users can create new data type, but they are not "real" data type but different zval values. And the number and definition of "real" data type are stable. Thus the size and content of stack won't change in run time.

  2. The size of memory is limited. PHP have to actively do reference counting and garbage collection. For more detail, please read this slide about PHP memory management.

like image 182
Koala Yeung Avatar answered Sep 22 '22 04:09

Koala Yeung