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 ...

Get Mastering The Faster Web with PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.