-
-
Save SchumacherFM/7035269 to your computer and use it in GitHub Desktop.
<?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 |
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 ;).
@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.
array_map(fn($num) => (int)$num, ['1', '2']);
Oooh. Thanks! :)