作者:小小号号-- | 来源:互联网 | 2023-05-17 15:23
Julien Pauli, PHP contributor and release manager, details what changed between PHP 5 and PHP 7, and how to migrate and make effective use of the language optimizations. All statements are documented with specific examples and Blackfire profiles. Fifth and last episode: Immutable arrays using 1,000 times less memory.
- Click to share on Reddit (Opens in new window)
- 13Click to share on Facebook (Opens in new window)13
- 3Click to share on LinkedIn (Opens in new window)3
- More
Here again, the gain between PHP 5 and PHP 7 is huge. PHP 5 needs to create 1,000 times the same array, resulting in 27 Mb of memory. In PHP 7 with OPCache, we are using 36 Kb of memory, something like 1,000 times less!
If you can make use of an immutable array, use it, it would be a shame to break immutability by writing code like this:
|
$a = 'value';
/* Don't do that */
$ar = ['foo', 'bar', 42, $a];
/* But prefer that : */
$ar = ['foo', 'bar', 42, 'value'];
|
Other considerations
So far, we’ve described some PHP internal tricks that explain why PHP 7 performs better than PHP 5. However, those are micro-optimizations for most workloads. You need huge amount of data or tight loops in your code to really benefit from those optimizations. These situations mostly occur when running PHP workers in the background instead of handling HTTP requests.
We’ve shown that in these cases, you can greatly improve resource consumption (CPU and memory) just by writing your code differently.
But as always, don’t trust your gut feelings about possible performance optimizations. Don’t blindly patch your code, use a profiler like Blackfire to confirm your hypothesis and check that your changes actually improve code performance.
Happy PHP 7’ing,