Performance Comparison of Foreach, Array_Map with Lambda, and Array_Map with Static Function
This article evaluates the performance differences among three approaches for transforming an array: using foreach, using array_map with lambda/closure functions, and using array_map with 'static' functions/methods.
foreach
$result = array(); foreach ($numbers as $number) { $result[] = $number * 10; } return $result;
Map with lambda
return array_map(function($number) { return $number * 10; }, $numbers);
Map with 'static' function, passed as string reference
function tenTimes($number) { return $number * 10; } return array_map('tenTimes', $numbers);
Performance Benchmarks
Benchmarks conducted using different PHP versions (5.6, 7, and HHVM) revealed the following results:
PHP Version | Foreach | MapClosure | MapNamed | MapClosureI | ForEachI |
---|---|---|---|---|---|
5.6 | 0.57 | 0.59 | 0.69 | 0.73 | 0.60 |
7 | 0.11 | 0.16 | 0.11 | 0.19 | 0.11 |
HHVM | 0.09 | 0.10 | 0.10 | 0.11 | 0.09 |
In general, foreach and array_map with lambda functions exhibited similar performance. Array_map with static functions was slightly slower. Using closures with use statements introduced a noticeable performance penalty.
Conclusion
The choice between these approaches depends on the specific use case and factors such as code readability, maintainability, and performance. For simple transformations, foreach and array_map with lambda functions offer comparable performance and provide a concise syntax. For more complex transformations, array_map with static functions allows for a cleaner and reusable code structure, albeit with a potential performance trade-off.
The above is the detailed content of Which PHP Array Transformation Method is Fastest: foreach, array_map with Lambda, or array_map with Static Function?. For more information, please follow other related articles on the PHP Chinese website!