Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masakielastic/5ec48dc3a8bb2c06356b to your computer and use it in GitHub Desktop.
Save masakielastic/5ec48dc3a8bb2c06356b to your computer and use it in GitHub Desktop.
mt_rand vs chr vs string concatenation
<?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);
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