Immutable and packed arrays

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

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.