Skip to content

Instantly share code, notes, and snippets.

@SchumacherFM
Created October 18, 2013 01:49
Show Gist options
  • Save SchumacherFM/7035269 to your computer and use it in GitHub Desktop.
Save SchumacherFM/7035269 to your computer and use it in GitHub Desktop.
array_map('intval',...) vs arrayToInt()
<?php
$integers = range(100, 1000);
foreach ($integers as &$int) {
$int = (string)$int;
}
function arrayToInt(array $arr)
{
foreach ($arr as &$a) {
$a = (int)$a;
}
return $arr;
}
$start = microtime(true);
$sum = 0;
for ($i = 0; $i < 100000; $i++) {
$converted = array_map('intval', $integers);
$sum += array_sum($converted);
}
var_dump($sum);
printf("\n%.6f msec\n", microtime(true) - $start);
flush();
$start = microtime(true);
$sum = 0;
for ($i = 0; $i < 100000; $i++) {
$converted = arrayToInt($integers);
$sum += array_sum($converted);
}
var_dump($sum);
printf("\n%.6f msec\n", microtime(true) - $start);
$ php -f arrayToInt.php
31.362757 msec
23.988653 msec
@SchumacherFM
Copy link
Author

Nice result for micro optimization 8-)

@parhamr
Copy link

parhamr commented Oct 18, 2013

Oooh. Thanks! :)

@banks
Copy link

banks commented Oct 18, 2013

You labeled the output 'msec' when it's really seconds. 7ms difference is ~80 pico seconds per element which is laughable.

Even so, I find it highly suspect that array_map is a real bottleneck here. I re-ran your gist with a second version of arrayToInt that was identical except used function call cast rather than operator (to get better comparison with array map which naturally has to call a function on each element).

<?php
// ...
function arrayToInt2(array $arr)
{
    foreach ($arr as &$a) {
        $a = intval($a);
    }
    return $arr;
}
// ...
array_map       35.559198 sec
arrayToInt      21.657530 sec
arrayToInt2     36.301321 sec

At any rate worrying about micro-optimisation like this seems misguided in all but the most extreme cases in PHP to be honest. If a few micro seconds here and there are so critical to your app then you probably shouldn't be writing it in PHP at all :).

My 2 cents: use array_map() if it is useful and makes your code cleaner, write C if PHP is too slow ;).

Copy link

ghost commented Apr 10, 2014

@banks A+

You said everything I was thinking as I read the original post.

You even wrote your function the way I would've.

Amen, my friend.

@cgfeel
Copy link

cgfeel commented Jul 26, 2022

array_map(fn($num) => (int)$num, ['1', '2']);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment