As we will see later in this chapter, immutability not only helps the developer lessen his cognitive burden while programming and makes for better quality code and better unit tests in general, but will also allow for better code optimizations by the compiler. As of PHP 7, any static array is cached by OPcache and a pointer to the array is shared with any part of the code that tries to access it. Moreover, PHP 7 offers a very important optimization for packed arrays, which are arrays that are indexed with ascending integers only. Let's take the following code and execute it against PHP 5.6 and then PHP 7 with OPcache enabled:
// chap3_immutable_arrays.php $start = microtime(true); for ($x = 0; $x < 10000; $x++) { $array[] = [ 'key1' => 'This is the first key', 'key2' => 'This is the second key', 'key3' => 'This is the third key', ]; } echo $array[8181]['key2'] . PHP_EOL; $time = microtime(true) - $start; echo 'Time elapsed: ' . $time . PHP_EOL; echo memory_get_usage() . ' bytes' . PHP_EOL;
If we run the previous code with PHP 5.6, we consume almost 7.4 MB of memory and the elapsed time is 0.005 seconds:
If we run the same code with PHP 7, we get the following result:
The results are impressive. The same script is 40 times faster and consumes almost 10 times less memory. Immutable arrays therefore provide more speed and developers should avoid modifying large arrays and encourage the use of packed arrays as much as possible when dealing with large arrays in order to optimize memory allocation and maximize speed at runtime.