PHP: array_map vs array_map with callback vs foreach

22nd June 2022, 04:05

So 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:

Runarray_maparray_map w/ callbackforeach
#12.8133391.9073481.096725
#22.2172921.0013585.960464
#32.1934501.5020379.059906
#42.7179711.5020379.059906
#52.8848641.287467.867813
#61.3828277.867815.006790
array_map / array_map (with callback) / foreach performance comparison

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.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


Recent posts

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 more
Javascript: Synchronous imports

Recently we’ve come across a challenge. Well not really a challenge for normal developers, but one for developers that like […]

Read more