Php quickly obtains a small random array in a large number Group.

Source: Internet
Author: User
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:

  1. $ Arr = range (1, 100000 );
  2. $ Start = time ();
  3. For ($ I = 0; I 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;

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:

  1. $ Arr = range (1, 100000 );
  2. $ Start = time ();
  3. For ($ I = 0; I 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;

The efficiency is improved by 3-4 times.

Group, php

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.