2013年6月24日星期一

Blake Gardner: Practical usage of PHP 5.5 generators: yield keyword


With the release of PHP 5.5 came a whole group of new features, including the "yield" keyword for better handling of values in iteration. Blake Gardner has posted a practical example of its use to his site today.



The key to understating the way the yield works verses a normal function is that rather than generating all of your data and returning the final array when it's done; you yield the value as it's generated. The state of the generator function is saved after you yield and then its state is restored when called again so the iteration can continue.


He shows a basic use of "yield" in a simple foreach of 1000000 values. In the first example, memory is exhausted and the second yields the values as they come, reducing the overhead significantly. The "range_yield" function returns them as the "for" loop generates them.


Link: http://blakegardner.co/2013/06/24/practical-usage-of-php-5-5-generators-yield-keyword

没有评论:

发表评论