Is the memory used by file_get_contents () freed when it is not assigned to a variable?

When I use file_get_contents and pass it as a parameter to another function without assigning it to a variable, does this memory free until the script completes?

Example:

preg_match($pattern, file_get_contents('http://domain.tld/path/to/file.ext'), $matches);

Will the memory used by file_get_contents be freed until the script completes?

+3
source share
4 answers

A temporary line created to store the contents of the file will be destroyed. Without going into the sources for confirmation, here are several ways to verify that the temporary value created as a function parameter will be destroyed:

Method 1: a class that reports its destruction

, , :

class lifetime
{
    public function __construct()
    {
         echo "construct\n";
    }
    public function __destruct()
    {
         echo "destruct\n";
    }


}

function getTestObject()
{
   return new lifetime();
}


function foo($obj)
{
   echo "inside foo\n";
}




echo "Calling foo\n";
foo(getTestObject());
echo "foo complete\n";

Calling foo
construct
inside foo
destruct
foo complete

, foo.

2:

, memory_get_usage, , .

function foo($str)
{
   $length=strlen($str);

   echo "in foo: data is $length, memory usage=".memory_get_usage()."\n";
}

echo "start: ".memory_get_usage()."\n";
foo(file_get_contents('/tmp/three_megabyte_file'));
echo "end: ".memory_get_usage()."\n";

start: 50672
in foo: data is 2999384, memory usage=3050884
end: 51544
+9

, $matches .
, .

0

= 6493720

start: 1050504

: 6492344

echo "start: ".memory_get_usage()."\n";
$data = file_get_contents("/six_megabyte_file");
echo "end: ".memory_get_usage()."\n";

= 1049680

start = 1050504

end = 1050976

echo "start: ".memory_get_usage()."\n";
file_get_contents("/six_megabyte_file");
echo "end: ".memory_get_usage()."\n";

: .

0

If you think that this will help to avoid memory errors, you are mistaken. Your code ( bytes_format ):

<?php
$url = 'http://speedtest.netcologne.de/test_10mb.bin';
echo 'Before: ' . bytes_format(memory_get_usage()) . PHP_EOL;
preg_match('~~', file_get_contents($url), $matches);
echo 'After: ' . bytes_format(memory_get_usage()) . PHP_EOL;
echo 'Peak: ' . bytes_format(memory_get_peak_usage(true)) . PHP_EOL;
?>

uses 10.5 MB:

Before: 215.41 KB
After: 218.41 KB
Peak: 10.5 MB

and this code:

<?php
$url = 'http://speedtest.netcologne.de/test_10mb.bin';
echo 'Before: ' . bytes_format(memory_get_usage()) . PHP_EOL;
$contents = file_get_contents($url);
preg_match('~~', $contents, $matches);
unset($contents);
echo 'After: ' . bytes_format(memory_get_usage()) . PHP_EOL;
echo 'Peak: ' . bytes_format(memory_get_peak_usage(true)) . PHP_EOL;
?>

also uses 10.5 MB:

Before: 215.13 KB
After: 217.64 KB
Peak: 10.5 MB

If you like to protect your script, you need to use the parameter $lengthor read the file in pieces .

0
source

Source: https://habr.com/ru/post/1702579/


All Articles