2

Dear gods of Stackoverflow

Let's say I have a MySQL query that selects a large dataset:

$query = "SELECT col_1, col_2, ..., col_99 FROM big_table";

And I get a MySQLi result like so:

$result = $db->query($query);

But then instead of dealing with $result in this scope, I pass it to a function:

my_function($result);

And once inside my_function(), I iterate through each row in the result and do stuff:

function my_function($result) {

    while($row = $result->fetch_object()) {
        ...
    }

}

Please help me understand the memory implications of this approach.

In other words, what does $result contain, and are there any pitfalls with passing it to a function? Should I consider passing $result by reference instead? For what it's worth, I won't be needing $result once my_function() is done with it.

Cheers from South Africa!

Kosta Kontos
  • 4,152
  • 7
  • 25
  • 28

3 Answers3

2

There are virtually no memory implications to this approach. PHP passes objects by reference, so very little memory is used when passing an object to a function.

The same is not quite true of arrays, they use a technique called Copy On Write, meaning that if you change an array inside a function then the array will be cloned.

You can always see for yourself what the impact is.

GordonM
  • 31,179
  • 15
  • 87
  • 129
2

You will not have any memory implications at all. $result holds a resource. It does not hold the whole result. It's just a resource Id of the result. MySQL uses this I'd to collect the result.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

Objects in PHP 5+ are automatically passed by reference, so passing the result object into a function won't duplicate it.

You can then unset the variable after the function has been called.

christopher_b
  • 958
  • 5
  • 13