Last active
August 29, 2015 14:27
-
-
Save masakielastic/5ec48dc3a8bb2c06356b to your computer and use it in GitHub Desktop.
mt_rand vs chr vs string concatenation
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 | |
function timer(callable $block) { | |
$start = microtime(true); | |
for ($i = 0; $i < 100000; ++$i) { | |
$block(); | |
} | |
$end = microtime(true); | |
return $end - $start; | |
} | |
$tests = [ | |
'mt_rand only' => timer(function() { | |
for ($i = 0; $i < 32; ++$i) { | |
mt_rand(0, 255); | |
} | |
}), | |
'mt_rand and chr' => timer(function() { | |
for ($i = 0; $i < 32; ++$i) { | |
chr(mt_rand(0, 255)); | |
} | |
}), | |
'mt_rand and chr and string concatenation' => timer(function() { | |
$buf = ''; | |
for ($i = 0; $i < 32; ++$i) { | |
$buf .= chr(mt_rand(0, 255)); | |
} | |
}) | |
]; | |
asort($tests); | |
var_dump($tests); |
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
array(3) { | |
["mt_rand only"]=> | |
float(0.45156311988831) | |
["mt_rand and chr"]=> | |
float(0.66792511940002) | |
["mt_rand and chr and string concatenation"]=> | |
float(0.80100607872009) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment