Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Evert Pot:
Save memory by switching to generators
Aug 11, 2015 @ 09:45:51

Evert Pot has a post to his site showing you to conserve memory with generators in your PHP scripts. Generators are a language feature that allows you to generate/manipulate data like an iterator without needing to pre-generate the array beforehand.

Since the release of PHP 5.5, we now have access to generators. Generators are a pretty cool language feature, and can allow you to save quite a bit of memory if they are used in the right places. [...] It's not uncommon in complex applications for the result of a function like our [example] to be passed to multiple functions that mangle or modify the data further. Each of these functions tend to have a (foreach) loop and will grow in memory usage as the amount of data goes up.

He uses a common example of fetching a set of articles from a database to show how memory consumption could get huge when a large number of articles are involved. He rewrites the example using generators instead, making use of the yield functionality to only fetch one record at a time and map it to the object structure. He also includes a few things to watch out for when using generators including the different return value of the method (iterator, not an array). He also points out an issue where the array_* functions will no work on iterators so you'd need to convert it back to an array before use.

tagged: memory generator switch example records yield

Link: http://evertpot.com/switching-to-generators/