Hey everyone!
So I've been experimenting with generators for the last couple days but I am not sure if I am doing it correctly or if my situation is one that would yield (heh...) the best results. Unfortunately I cannot post source code since it would probably result in me being fired or worse, but I think I can accurately describe my situation.
I am calling a web service provided by the client that returns a very large JSON object. I am applying json_decode() on it and then performing a foreach() and executing commands on each item in it (creating an object, checking some values, then inserting into a database with prepared statements). The issue is the memory footprint is quite large because I am assuming the JSON object returned by the web service has to be loaded into memory. I thought maybe I could utilize generators since the most obvious appeal of them is the very low memory footprint they require.
However, while I can get the generator to work and the script runs as it's supposed to (all expected entries are inserted into the database correctly), the memory footprint remains identical to what it was before. So I am wondering if I am doing something wrong or if simply my situation doesn't apply. I'll try to describe it better below:
- Query web service and retrieve JSON response
- Apply json_decode() on the response to create a standard class object.
- Perform foreach() on said standard class object and yield each result
- Call the function doing the yield and do the necessary actions on each yielded item
In fact, let me see if I can accurately describe this in some dummy code:
function retrieveData()
{
// bunch of curl() stuff
$response = curl_exec($ch);
// check response, etc.
foreach (json_decode($response)->d->results as $value) {
yield $value;
}
}
foreach (retrieveData() as $value) {
importData($value);
}
function importData($value)
{
// do stuff to the $value
}
I found an example similar to what I am doing (kinda) but the author is seeing the obvious memory footprint benefits, whereas I am not. Here's a link to the example: http://syrwebdev.com/php/2015/01/22/experimenting-with-php5.5-generators.html. Is it because my example is so much larger than the author's?
The memory before the script performs the import: ~367KB
The memory immediately after the script completes the import: ~200MB
For what it's worth this is being performed on PHP 5.6. We would love to do this on 7 but the client is running the SqlSrv extension which only has a release candidate out (just a couple days ago), so not ready for production yet.
Would appreciate any insight! Thank you!