An introduction to the analysis and pros and cons of iterators and generators in PHP

Source: Internet
Author: User
This article brings the content is about PHP in the iterator and generator analysis and advantages and disadvantages of the introduction, there is a certain reference value, the need for friends can refer to, I hope to help you.





First. iterators






Analysis : Think about it, if we put together the collection object and the operation of the collection object, when we want to iterate over the elements of the collection object in a different way, we need to modify the collection object, violate the "single responsibility Principle", and the iterator pattern will separate the data structure and data structure, and the two can develop independently.



Advantages:



1. Supports multiple traversal methods. For example, there is a sequence table, we can provide a positive sequence traversal, reverse-traverse two kinds of iterators as needed. The user only needs to get our iterators, and we can perform traversal operations on the collection.



2. The aggregation class is simplified. Because of the introduction of Iterators, the original collection objects do not have to traverse the collection elements themselves.



3. Adding new aggregation classes and iterator classes is convenient, two dimensions can be independent of each other



4. Provides a unified interface for different collection structures, enabling the same algorithm to operate on different sets of structures



Disadvantages:



1. Iterator mode adds a new collection object to the separation of responsibility for storing data and traversing data add the corresponding iterator class, increase the number of classes in pairs, and increase the complexity of the system to some extent



Specific interface:



Iterator extends Traversable {
/ * Method * /
abstract public mixed current (void)
abstract public scalar key (void)
abstract public void next (void)
abstract public void rewind (void)
abstract public bool valid (void)
}


Second. Generator



PHP Generator (Generator) is a feature introduced by PHP5.5.0, unlike a standard PHP iterator, the PHP generator does not require the class to implement the iterator interface, thus alleviating the burden of the class, and the generator calculates and outputs the values to iterate on demand, which has a significant impact on performance. Imagine if a standard PHP iterator often performs iterative operations in memory in advance The performance of the data set is poor, and if you want to calculate large amounts of data in a specific way, the performance impact is even greater. At this point we can use the generator to calculate the output subsequent values without consuming valuable memory resources.



Advantages: Low memory consumption, good performance. Each time a value is produced, the internal state of the generator pauses, and the internal state resumes when the next value is requested by the generator. The inside of the generator is always switched between pause and resume until the loop completes or pauses



Disadvantages:



The 1.PHP generator does not meet the requirements of all iterators, because if you do not query, the generator never knows what the next iteration value is, and cannot back or forward in the generator.



2. The generator is also one-time and cannot iterate the same generator multiple times, but you can rebuild or clone the generator if you want.



Create generator:



1. Because the generator is a PHP function, the generator is using the yield keyword in the function. Unlike normal PHP functions, the producer never returns a value, only the value is output.




<?php
function myGenerator(){
    yield 'a';
    yield 'b';
    yield 'c';
}


2. When invoking the generator function, PHP returns an object belonging to the generator class. This object can be iterated using the foreach () function. For each iteration, PHP requires the generator instance to compute and provide the next value to iterate




<?php
function makeRange($length){
    for($i = 0; $i<$length; $i++){
        yield $i;
    }
}

foreach(makeRange(1000000) as $i){
    echo $i,PHP_EOL;
}


As shown above: When the $length is very large (millions), and you do not use the generator at the same time, it is necessary to pre-allocate memory for an array consisting of 1 million 1500 integers. The PHP generator can do the same thing, but it only allocates memory for an integer at a time.


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.