Php quickly obtains a small random array in a large number Group.
You can click another group to refresh the recommended content. First, query the database to obtain the first 1000 data records, and then randomly remove four data records. After the program is written, it is found that the operation is very slow. every time you refresh the program, it takes a long time to come out. The code is as follows:
- $ Arr = range (1, 100000 );
- $ Start = time ();
- For ($ I = 0; I I <100; $ I ++ ){
- $ Key = mt_rand (0, 99999-$ I );
- $ Result [] = $ arr [$ key];
- Unset ($ arr [$ key]);
- Sort ($ arr );
- }
- $ End = time ();
- Echo $ end-$ start;
The preceding statement must be sorted after unset is used. Unset only deletes the key value, while the key is retained. The improved method is as follows:
- $ Arr = range (1, 100000 );
- $ Start = time ();
- For ($ I = 0; I I <100; $ I ++ ){
- $ Key = mt_rand (0, 99999-$ I );
- $ Result [] = array_splice ($ arr, $ key, 1 );
- }
- $ End = time ();
- Echo $ end-$ start;
The efficiency is improved by 3-4 times. |
Group, php