
For(each) alternatives: introducing “array_map” and “array_filter”
Being a programmer, you’re probably very (very) familiar with the for and foreach loops in PHP and Javascript. So familiar […]
Read moreSo we’ve come across plenty of posts comparing / measuring performance of the PHP array_map
function vs foreach
.
So we decided to measure the performance for ourselves to see what’s faster. Here’s the script to check the performance speed:
<?php
function generate()
{
$data = [];
for ($i = 0; $i < 100; $i++) {
$data[] = [
'id' => $i,
'data' => [
'title' => "Item {$i}"
]
];
}
return $data;
}
$data = generate(100);
$now = microtime(true);
$map = array_map(function ($entry) {
return $entry['data']['title'];
}, $data);
echo "array_map: " . (microtime(true) - $now) . "\n";
$data = generate(100);
$now = microtime(true);
function map($entry)
{
return $entry['data']['title'];
}
$map = array_map('map', $data);
echo "array_map w/ callback: " . (microtime(true) - $now) . "\n";
$data = generate(100);
$now = microtime(true);
$out = [];
foreach ($data as $entry) {
$out[] = $entry['data']['title'];
}
echo "foreach: " . (microtime(true) - $now) . "\n";
Important to note is that the script creates a new set of data, before running each set. This is due to PHP indexing arrays, so we want to avoid that.
Anyway, here are the results:
Run | array_map | array_map w/ callback | foreach |
#1 | 2.813339 | 1.907348 | 1.096725 |
#2 | 2.217292 | 1.001358 | 5.960464 |
#3 | 2.193450 | 1.502037 | 9.059906 |
#4 | 2.717971 | 1.502037 | 9.059906 |
#5 | 2.884864 | 1.28746 | 7.867813 |
#6 | 1.382827 | 7.86781 | 5.006790 |
array_map
(with a callback) seems to be the winner for speediest boy!
However, when we take all results into account, we can see that array_map
with a closure
seems to be the most consistent performer.
This came to our suprise since our assumption was that array_map
with an inline closure
would win due to it being embedded into the working memory of PHP. This however, doesn’t seem to be the case and apparently the string
callback is instead being treated like a memory-pointer.
foreach
has also done well, but seems to be performing very inconsistent. Ending up on the #1 spot in the first run, but after that it all went down hill.
So there we have it: use array_map
with string
-callbacks when possible and try to avoid foreach
loops to map array data when you’re really depending on performance.
Being a programmer, you’re probably very (very) familiar with the for and foreach loops in PHP and Javascript. So familiar […]
Read moreRecently we’ve come across a challenge. Well not really a challenge for normal developers, but one for developers that like […]
Read more
Leave a Reply