Home > Backend Development > PHP Tutorial > PHP quickly gets random small arrays in large arrays

PHP quickly gets random small arrays in large arrays

WBOY
Release: 2016-07-25 08:43:12
Original
1010 people have browsed it

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:

  1. $arr = range(1, 100000);
  2. $start = time();
  3. for($i = 0; $i < 100; $i ++){
  4. $key = mt_rand(0, 99999 - $i);
  5. $result[] = $arr[$key];
  6. unset($arr[$key]);
  7. sort($arr);
  8. }
  9. $end = time( );
  10. echo $end - $start;
Copy code

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 is as follows:

  1. $arr = range(1, 100000);
  2. $start = time();
  3. for($i = 0; $i < 100; $i ++) {
  4. $key = mt_rand(0, 99999 - $i);
  5. $result[] = array_splice($arr, $key, 1);
  6. }
  7. $end = time();
  8. echo $end - $start;
Copy code

Efficiency increased by 3-4 times.

In the group, php


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template