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

SitePoint PHP Blog:
Memory Performance Boosts with Generators and Nikic/Iter
Oct 20, 2015 @ 14:31:24

On the SitePoint PHP blog there's a tutorial posted showing you how to get some performance gains in your PHP applications using the "Iter" library from Nikita Popov.

First came arrays. Then we gained the ability to define our own array-like things (called iterators). But since PHP 5.5, we can rapidly create iterator-like structures called generators. These appear as functions, but we can use them as iterators. They give us a simple syntax for what are essentially interruptible, repeatable functions. They’re wonderful!

And we’re going to look at a few areas in which we can use them. We’re also going to discover a few problems to be aware of when using them. Finally, we’ll study a brilliant library, created by the talented Nikita Popov.

They start with a common problem: loading information line-by-line from a CSV file. They do some filtering and merging of the values but point our a major flaw - large files. These would drag down performance quite a bit and generators might just make for a good solution. He shows a simple "read CSV" generator to get the lines in the file while also reducing the memory needed. Unfortunately the array_map/array_filter methods he was using for sorting don't work with generators. The nikic/iter helps fix this. Code examples are included showing it in use performing the same operations as before. He ends the post with a few other "fun things" including array flattening, slicing and rewinding generators.

tagged: memory performance boost generator nikic iter library tutorial

Link: http://www.sitepoint.com/memory-performance-boosts-with-generators-and-nikiciter/


Trending Topics: