I am trying to get REAL size (memory usage) of a variable in PHP. I know there is no straightforward method to achieve this but there is a simple "hack" using memory_get_usage().
<?php
function varSize()
{
$s = memory_get_usage();
$x = true;
echo memory_get_usage() - $s;
}
varSize();
echo '<br>';
$s = memory_get_usage();
$x = true;
echo memory_get_usage() - $s;
echo '<br>';
$s = memory_get_usage();
$x = unserialize(serialize(true));
echo memory_get_usage() - $s;
?>
This code returns 64, 160, 0 respectively. The hell why? The two first variants is an absolute copy-paste of each other! Why is this happens and how to get a real variable size?
allocated; so in the 2nd example it allocated 160 more that whatever it had, next it did not deallocate, in the 3rd example it apperently did not need more, thereformemory_get_usage() - $s = 0memory_get_usagedoes not report mem-usage per variable or similar, but per (de-)allocated "chunk" of mem. Say php starts with 0.5Mb, then you do some stuff and it decides it needs 1Mb more, you will only be able to measure the change from 0.5Mb to 1.5Mb because it measures memory allocation. That is in contrast to memory per variable usage. It will almost allways allocate more than it needs right now, since allocating memory is not free, and it tries to keep the calls to alloc at a reasonable minimum.