0

Does the garbage collector can collect elements which belongs to a script that is under sleep() condition?

I know that the garbage collector free objects from memory if they aren't referenced (so they are considered to be no more in use).

If the answer is yes, I can free resources before the script continues, so with a higher execution time I can use less memory.

Is my reasoning true?

I'll try to be clearer:

  • the script is running
  • in the script I make 3 variables eligible for being garbage collection: $var1 = $var2 = $var3 = null; or other form to make it properly, this isn't the point
  • in the script I invoke sleep(100);
  • here is where my question applies: before the time of 100 seconds ends, does the garbage collector can run to free $var1, $var2 and $var3?

Thanks a lot.

user2342558
  • 5,567
  • 5
  • 33
  • 54

1 Answers1

1

I think the space of deleted variables is released immediately. Use memory_get_usage() to determine your required memory. This is shown by the following small test:

<?php
    echo memory_get_usage(false)." start <br>";
    $var1 = range(0,10000);  //a big array
    echo memory_get_usage(false)." create var1 <br>";
    unset($var1);  
    echo memory_get_usage(false)." unset var1 <br>";

Output:

424120 start 
952560 create var1 
424120 unset var1 
jspit
  • 7,276
  • 1
  • 9
  • 17
  • If a variable falls out of scope and is not used in any other place of the currently executed code anymore, then it is garbage collected automatically. You can force this early by using unset() to end variables scope early. What can the garbage collector do, if you clean up self all? – jspit Oct 09 '19 at 11:49