PHP source memory for include file

Can I free the memory generated from the included file, here are my codes

a.php

<?
echo memory_get_usage();
include_once "b.php";
echo memory_get_usage();
$n = new obj();
echo memory_get_usage();
?>

b.php

<?
class obj {
protected $_obj = array{
....
}

function ....

}

?>

I checked that after enabling b.php, memory usage will increase, which is higher than creating a new object. Result below

348832 496824 497072

So how can I free included file memory?

+3
source share
3 answers

I think that PHP cannot de-enable (I mean, free up memory space due to the included file), since the contents of the file can be used later. This is the design choice of the creators of PHP.

PHP script , , , .

(, ) , , , unset($obj). . PHP Garbage Collection, .

+3

PHP / , , php , script.

/ , , ( , b.php).

, php , b.php(include_ONCE), , , ( , ).

ahmet alp balkan, script, , , unset(); PHP , unset, "". (+ , , , ). GC .

, , :

<?
echo memory_get_usage();
include_once "b.php";
echo memory_get_usage();
$n = new obj();
echo memory_get_usage();
unset($n);
echo memory_get_usage();
// try to wait for GC
sleep(5);
echo memory_get_usage();
?>
+2

, , $x = file_get_contents() , preg_match().

, $x . , , , , . :

/* You need the value of $modx->lang_attribute and there is something like this
   in the file: $modx_lang_attribute = 'en'; */
$x = file_get_contents('path/to/file');
$pattern = "/modx_lang_attribute\s*=\s*'(\w\w)'/";
preg_match($pattern, $x, $matches);
return isset($matches[1])? $matches[1] : 'en';

In some cases, you can save more memory by processing the file line by line.

The downside of this file is that the file will not be marked, so it will take up more memory when used, but at least you won’t transfer it for the rest of the program.

+1
source

All Articles