The total number of elements in your array is just over 100,000.
Each element of your array is just one byte (logical), so for more than 100,000 elements, it takes 100,000 bytes ~ 0.1 MB
Each of your objects is ~ 100 bytes, this is 100 * 100000 = 100000000 bytes ~ 10 MB
But you have ~ 18 MB, so where is it 8 of?
If you run this code
<?php $c = 0; //we use this to count object isntances class obj{ protected $name; protected $children = array(); public static $c=0; public function __construct($name){ global $c; $c++; $this->name = $name; } public static function build($name, $array = array()){ global $c; $b = memory_get_usage(); $obj = new self($name); $diff = memory_get_usage()-$b; echo $c . ' diff ' . $diff . '<br />'; //display change in allocated size if(is_array($array)){ foreach($array as $k => $v) $obj->addChild(self::build($k, $v)); } return $obj; } public function addChild(self $child){ $this->children[] = $child; } public function toHTML(){ $html = '<div>' . $this->name . '</div>'; $html .= '<ul>'; foreach($this->children as $child) $html .= '<li>' . $child->toHTML() . '</li>'; $html .= '</ul>'; return $html; } } $big = array_fill(0, 500, true); $big[5] = array_fill(0, 200, $big); $root = obj::build('root', $big);
You will notice that the change is permanent with the exception for objects created as 1024th, 2048th, 4096th ...
I don’t have a link to any article or manual page about this, but I assume that php holds links to each created object in an array with an initial size of 1024. When you make this array full, its size will be doubled to make space for new objects .
If you differ from, for example, the 2048th object, subtract the size of the object (the constant value that you have on the other lines) and divide by 2048, you will always get a 32-standard pointer size in C.
So, for 100,000 objects, this array has grown to the size of 131072 elements. 131072 * 32 = 4194304B = 4 MB
This calculation is approximate, but I think it answers your question, which takes up so much memory.
To answer the question of how to save memory, avoid using objects for a large data set.
Obviously, objects are nice and simple, but primitive data types are faster and smaller.
Perhaps you can make it work with a single object containing an array of data. It is difficult to propose an alternative without additional information about these objects and what methods / interface they require.