Home  >  Article  >  php教程  >  PHP quickly gets random small arrays in large arrays

PHP quickly gets random small arrays in large arrays

大家讲道理
大家讲道理Original
2016-11-11 09:45:291260browse

There is a function to guess what users like. Users can refresh the recommended content by clicking to change a group.

First query the database to get the first 1000 pieces of data, and then randomly remove 4 pieces.

After I finished writing the program, I found that it ran very slowly. Every time I refreshed it, I had to wait a long time for it to come out.

The code is as follows:

$arr = range(1, 100000);
$start = time();
for($i = 0; $i < 100; $i ++){
    $key = mt_rand(0, 99999 - $i);
    $result[] = $arr[$key];
    unset($arr[$key]);
    sort($arr);
}
$end = time();
echo $end - $start;

The above writing method must be sorted after using unset.

unset will only delete the key value, but the key will be retained.

The improved writing method is as follows:

$arr = range(1, 100000);
$start = time();
for($i = 0; $i < 100; $i ++){
    $key = mt_rand(0, 99999 - $i); 
    $result[] = array_splice($arr, $key, 1);
}
$end = time();
echo $end - $start;

The efficiency has increased by 3-4 times.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn