2

I am writing some php scripts that deal with a lot of data but in chunks at a time within functions. kind of like this:

function part1(){
  $data = getLargeArray();
  $evenBigger = array();
  foreach($data as $piece){
    $evenBigger[$piece['part1']][$piece['part2']][] = ohGodMoreData();
  }

  //...manipulate $evenBigger more and more

  return true;
}

part1();

part2();
//...etc

I am concerned about the memory usage of my functions. Not that they are terribly burdensome, but I fear that if the memory is not freed it might be. I know php frees all of its memory at the end of each script, but I also don't want to run 4 or 5 different scripts.

When I move onto part2(); is the memory freed from part1();?

Should I manually unset the variables that take up so much space such as $data and $evenBigger or trust that php will do this for me when the function ends?

Alternatively:

-Is there a better way to let go of that memory?

-Any way to test such a thing?

-Any tips for better resource management?

bobkingof12vs
  • 610
  • 5
  • 21
  • 1
    memory_get_usage() use it, and you can answer your own questions –  Mar 03 '14 at 22:14
  • 1
    Memory isn't `freed`, but the memory used by variables that lie only within the scope of the function is made available for `garbage collection` when the function returns or exits, and `garbage collection` will release the memory when it has a spare clock cycle or two in which to do so... generally this will happen pretty quickly – Mark Baker Mar 03 '14 at 22:21
  • 1
    You can manually `unset` variables within a function, but again this only makes them available for `garbage collection` – Mark Baker Mar 03 '14 at 22:23

1 Answers1

0

PHP doesn't expect you to unset all your variables.

Here your $evenBigger variable has a local scope, unless you assigned it to some external reference somewhere in your code, you don't need to handle it after the execution of your function.

Note that I don't know exactly the inner behavior of PHP and I can't tell when exactly this will be garbage collected. The doc about is seems nice http://www.php.net/manual/en/features.gc.php

AsTeR
  • 6,543
  • 12
  • 54
  • 91