The other day I was working on some sample code to test out an idea that involved an object with an internal nested array. This is a pretty common pattern in PHP: You have some simple one-off internal data structure so you make an informal struct using PHP associative arrays. Maybe you document it in a docblock, or maybe you're a lazy jerk and you don't. (Fight me!) But really, who bothers with defining a class for something that simple?
But that got me wondering, is that common pattern really, you know, good? Are objects actually more expensive or harder to work with than arrays? Or, more to the point, is that true today on PHP 7 given all the optimizations that have happened over the years compared with the bad old days of PHP 4?
So like any good scientist I decided to test it: What I found will shock you!
Most programmers write code for an abstract computer. The thing is- code runs on a real computer that works in a specific way. Even if your game is going to run on a wide range of devices, knowing some of the common features can speed up your code 10x or more. Today’s article shows you how!
Broadly, all modern computers have the same configuration. They have a CPU, a GPU, and RAM. The CPU also has two or three levels of cache: L1, L2, and L3. Those caches are used to speed up RAM access because it is so slow. Exact numbers will vary by device, but according to this site here are the rough speeds:
L1 cache access: 1 nanosecond
L2 cache access: 4 nanoseconds
RAM access: 100 nanoseconds
This means that there’s a 25-100x advantage to using the memory that’s in the CPU’s cache compared to memory that’s in RAM.
zend_try_compile_special_func
Fonctions optimisées en php.
PHP Performance with Marco Pivetta (ocramius)
In this episode, Benjamin and Matthew talk with long-time open source contributor, and Roave member, Marco Pivetta about increasing the performance of PHP-based applications (both large and small) and dive deep into PHP 7.4's new Preloading functionality.
Play Episode Download (41.2 MB)
In this episode, Benjamin and Matthew, talk with Marco Pivetta (ocramius) about:
- PHP 7.4's new preloading feature: what it is, how it works, the benefits and drawbacks of using it
- The speed differences between different versions of PHP (especially in 7.x)
- The difference between OPcache and Preloading
- How Composer's autoloader may soon be a thing of the past
Notable Quotes
Composer is the mother of all frameworks.
The (Composer) autoloader will gradually disappear.
You wouldn't build a house and not check it for 10 years. It should be the same for software projects.
Everything (in software development) is a trade-off.
Links
- https://tideways.com/profiler/blog/5-ways-to-increase-php-performance
- https://wiki.php.net/rfc/preload
- Roave/you-are-using-it-wrong
- Roave/BackwardCompatibilityCheck