file_get_contentsを使用して、パラメーターとして別の関数に渡すと、変数に割り当てることなく、スクリプトの実行が終了する前にそのメモリがリリースされますか?
例えば:
preg_match($pattern, file_get_contents('http://domain.tld/path/to/file.ext'), $matches);
file_get_contents によって使用されたメモリは、スクリプトが終了する前に解放されますか?
file_get_contentsを使用して、パラメーターとして別の関数に渡すと、変数に割り当てることなく、スクリプトの実行が終了する前にそのメモリがリリースされますか?
例えば:
preg_match($pattern, file_get_contents('http://domain.tld/path/to/file.ext'), $matches);
file_get_contents によって使用されたメモリは、スクリプトが終了する前に解放されますか?
ファイルの内容を保持するために作成された一時的な文字列は破棄されます。ソースを掘り下げて確認することなく、関数パラメーターとして作成された一時的な値が破棄されることをテストできるいくつかの方法を次に示します。
これは、それ自体の終焉を報告するクラスを使用して寿命を示しています。
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 関数呼び出しの直後に破棄されることを示しています。
これは、 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
In your example the memory will be released when $matches
goes out of scope.
If you weren't storing the result of the match the memory would be released immediately
次のコードのメモリ使用量 = 6493720
開始: 1050504
終了: 6492344
echo "start: ".memory_get_usage()."\n";
$data = file_get_contents("/six_megabyte_file");
echo "end: ".memory_get_usage()."\n";
ただし、次のコードのメモリ使用量 = 1049680
開始 = 1050504
終了 = 1050976
echo "start: ".memory_get_usage()."\n";
file_get_contents("/six_megabyte_file");
echo "end: ".memory_get_usage()."\n";
注: 最初のコード ファイルでは、変数に格納されます。
これがメモリ不足エラーを回避するのに役立つと思うなら、あなたは間違っています。あなたのコード ( 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;
?>
10.5 MB を使用:
Before: 215.41 KB
After: 218.41 KB
Peak: 10.5 MB
そしてこのコード:
<?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;
?>
10.5 MB も使用します。
Before: 215.13 KB
After: 217.64 KB
Peak: 10.5 MB
スクリプトを保護したい場合は、$length
パラメーターを使用するか、ファイルをチャンクで読み取る必要があります。