Get a quick look at the PHP iteration Builder yield

Source: Internet
Author: User

Yield is from the beginning of PHP5.5, about the yidle of the description of the bird Brother's blog To do a detailed explanation, I think it is a bit complicated, in the read a few other posts there are cases, I probably know that the role of yield is in doing a lot of data cycle processing, can save a large part of memory ~

Official: http://php.net/manual/zh/language.generators.syntax.php

Brother Bird: http://www.laruence.com/2015/05/28/3038.html

Reference cases illustrate the role of yield

<?PHP//code for Normal modefunction Generatedata ($max) {$arr= [];  for($i =0; $i <= $max; $i + +) {$arr []=$i;}} Echo'pre-start memory consumption:'. Memory_get_usage (). Php_eol; $data= Generatedata (100000); Echo'memory consumption after generating array:'. Memory_get_usage (). Php_eol;unset ($data); Echo'memory consumption after release:'. Memory_get_usage (). Php_eol;
yield . Before PHP starts memory consumption: 387600 memory consumption after generating array: 387632 memory consumption after release: 387632

The memory difference used before and after is: 387632-387600 = 32

yield . Before PHP starts memory consumption: 386912 memory consumption after generating array: 387520 memory consumption after release: 386944

The memory difference used before and after is: 387520-386912 = 608

Obviously 608 is far greater than 32, not to say that it is to reduce memory utilization. Then adjust the value of the loop to try it. Change 100000 to 10000000

Use the CLI mode again to find out that the yield will be an error.

PHP Fatal Error:  134217728134217736 in/data/wwwroot/default7

But yield is still 608, because it is itself, and it produces real data when you iterate.

So if your data source is very large, then use yield. If the data source is small, of course you choose to load the memory once.

Get a quick look at the PHP iteration Builder yield

Related Article

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.