Introduction and examples of php generators

Source: Internet
Author: User
The generator provides an easier way to implement simple object iteration, but does not implement the performance overhead and complexity of a class with an Iterator interface. Note: PHP5.5 and later versions support generators.

The generator provides an easier way to implement simple object iteration, but does not implement the performance overhead and complexity of a class with an Iterator interface.

The generator allows you to write code in the foreach code block to iterate a group of data without creating an array in the memory. This will limit your memory or occupy a considerable processing time. On the contrary, you can write a generator function, just like a normal custom function. different from a normal function, a generator can return multiple times as needed, to generate the value to be iterated.

A simple example is to use a generator to re-implement the range () function. The standard range () function generates an array for each returned value in the memory and generates a large array. For example, calling range (0, 1000000) will cause memory usage to exceed 100 MB.

As an alternative, we can implement an xrange () generator. we only need enough memory to create an Iterator object and track the current state of the generator internally, this requires less than 1 kB of memory.

Example #1 implement range () as a generator

 = 0) {throw new LogicException ('step must be a negative number');} for ($ I = $ start; $ I >=$ limit; $ I + = $ step) {yield $ I ;}}/ * Note that the results of range () and xrange () are in the unified output below. */echo 'single odd number from range (): '; foreach (range (1, 9, 2) as $ number) {echo "$ number ";} echo "\ n"; echo 'single odd number from xrange () '; foreach (xrange (1, 9, 2) as $ number) {echo "$ number" ;}?>

The above routine will output:

Single digit odd numbers from range():  1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9

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.