Memory allocation of integers and floats

Another optimization introduced by PHP 7 is the reuse of previously allocated variable containers. If you need to create a large number of variables, you should try to reuse them, as PHP 7's compiler will avoid reallocating memory and reuse the memory slots that are already allocated. Let's have a look at the following example:

// chap3_variables.php 
 
$start = microtime(true); 
 
for ($x = 0; $x < 10000; $x++) { 
    $$x = 'test'; 
} 
 
for ($x = 0; $x < 10000; $x++) { 
    $$x = $x; 
} 
 
$time = microtime(true) - $start; 
 
echo 'Time elapsed: ' . $time . PHP_EOL; 
 
echo memory_get_usage() . ' bytes' . PHP_EOL; 

Let's run this code against PHP 5.6 and PHP 7 in order to see the difference in memory consumption. Let's start with PHP 5.6:

The results when running the script against PHP 5.6

Now, let's run the same script with PHP 7:

The results when running the same script against PHP 7.1

As you can see, the results show us that memory consumption was reduced by almost a third. Although this goes against the very principle of the immutability of variables, it is still a very important optimization when you must allocate a large number of variables in memory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset