Alex Rivera | Logout

In PHP, what happens in memory when we use mysql_query

Asked 2011-08-31T07:34:24.113
12

I used to fetch large amount of data using mysql_query then iterating through the result one by one to process the data. Ex:

$mysql_result = mysql_query("select * from user");
while($row = mysql_fetch_array($mysql_result)){
    echo $row['email'] . "\n";
}

Recently I looked at a few framework and realized that they fetched all data to an array in memory and returning the array.

$large_array = $db->fetchAll("select * from user");
foreach($large_array as $user){
    echo $user['email'] . "\n";
}

I would like to know the pros/cons of each method. It appears to me that loading everything in memory is a recipe for disaster if you have a very long list of items. But then again, a coworker told me that the mysql driver would have to put the result set in memory anyway. I'd like to get the opinion of someone who understand that the question is about performance. Please don't comment on the code, I just made it up as an example for the post.

Thanks

Edit
Report

1 Answer

-2

Just something I learned when it comes to performance: foreach is faster than a while loop. Perhaps you should benchmark your results of each and see which one is faster and less memory intensive. IMHO, I like the latter approach better. But do you really need every single column within the user table? If not, than just define the columns that you need instead of using * to grab them all. Since this will also help with memory and speed as well.

answered 2011-08-31T07:41:35.553

Your Answer