Created
October 18, 2013 01:49
-
-
Save SchumacherFM/7035269 to your computer and use it in GitHub Desktop.
array_map('intval',...) vs arrayToInt()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ php -f arrayToInt.php | |
31.362757 msec | |
23.988653 msec |
@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']);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).
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 ;).