I did some tests in the browser with the library pTester :
<?php
require 'pTester/ptester.php';
use ironwoods\tools\ptester\PTester;
function test_one(array $base): void
{
$x = $base[rand(0, count($base)-1)];
}
function test_two(array $base): void
{
$x = array_rand(array_flip($base), 1);
}
/**
* Tests
*
*/
$base = [
'root',
'user',
'admin',
'hack',
'cloud',
'apple',
'linux',
'blue',
'dark',
'pink',
'free',
'chard',
'ligth',
'moon',
'teen',
];
$arr_with_tests = [
test_one($base),
test_two($base),
];
PTester::setNumberOfRunningTests(2000);
PTester::setRunningCycles(TRUE);
PTester::test($arr_with_tests);
If you repeat several times:
Tested method number: 1
Used time: 7.65061378479E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 2
Used time: 7.8002333641052E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 1
Used time: 7.4004173278809E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 2
Used time: 7.5004696846008E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 1
Used time: 7.7004194259644E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 2
Used time: 8.3004355430603E-8 miliseconds
Used memory: 0 bytes.
If I am interpreting the result correctly it seems that the first method is somewhat slower .
Plus: use mt_rand () instead of rand ()
It is recommended to use mt_rand()
which is faster than rand()
, it also seems that rand()
has other problems and is completely replaced in the latest versions of PHP. See this thread about differences .
If we repeat the tests, using mt_rand () instead of rand () we would have:
Tested method number: 1
Used time: 8.1004023551941E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 2
Used time: 7.700502872467E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 1
Used time: 6.9506883621216E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 2
Used time: 8.0002188682556E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 1
Used time: 7.7004432678223E-8 miliseconds
Used memory: 0 bytes.
Tested method number: 2
Used time: 8.2505106925964E-8 miliseconds
Used memory: 0 bytes.