2 Replies to “Effizient zufällige Elemente aus großem PHP Array ziehen”
Comments are closed.
Dipl. Inform. Fabian Schmengler | Magento Certified Developer | Magento Certified Solution Specialist
Comments are closed.
Vor etwa 5-6 Jahren hatte ich meine "PHP sollte mehr wie Java sein" Phase und habe viel mit Sachen wie...
Maybe i am wrong, but i think that call count() in a while-loop is a performance loss because it will be called in each loop? Additionally, count() on the $array will be executed at least twice (the second one in the mt_rand()-line).
So i think that this would be better:
$arrayLength = count($array);
$randomArray = [];
while ($arrayLength < $k) {
$randomKey = mt_rand(0, $arrayLength - 1);
$randomArray[$randomKey] = $array[$randomKey];
}
I thought it would not make much difference but you are right, with
$arrayLength = count($array)
and using that inmt_rand
we can even improve the results a bit more. However, don’t use$arrayLength
in the while-condition, there we need to check the size of the result array.