Php memory size management - php

im having some trouble with one of my scripts, basically my scripts updates some products, but since is a lot of products if i dont manage carefully the php memoery from my script i get a error of memoery usage, so basically i used unset to release the memory space, now is much better but is not perfect, so im looking on the php docs and i notice a function called memoery_get_usage() to evaluate my script, i found online a simple example of using this method, but something strange is happening that i cant understand why is giving me this result. Basically i created a variable and store some data using a loop and check the memory between the begginning, after the script finish the loop and than when i unset, but the numbers or not what i expect.
Example script:
echo memory_get_usage(). PHP_EOL ;
$a = '';
for($i=0;$i<=100000;$i++){
$a[] = $i;
}
echo memory_get_usage(). PHP_EOL;
unset($a);
echo memory_get_usage(). PHP_EOL;
The results are:
222048
14871264
222232
The strange part is the last numbers, "222232", if i unset the variable, isnt expected to have the initial number memory at the beginning ("222048")?
Hope for someone could explain me.

Related

echo vs variable

Let's say I have $variable holding more than 500 kb info.
while ($row = mysqli_fetch_assoc($selectFromTable))
{
$variable .= "<p>$row[info]</p>";
}
or
while ($row = mysqli_fetch_assoc($selectFromTable))
{
echo "<p>$row[info]</p>";
}
Optimization wise, is it better to echo the info right away than saving it to a variable?
I can't decide because I can't see the difference in performance because I don't know what tool to use in monitoring the response time. Any suggestion?
Even though there is not enough difference in performance, I still wanted to learn on how can I optimize my coding.
There is no significant difference in speed or memory usage between the two pieces of code you listed. They both build a new string that contains the value of $row['info'] enclosed in a <p> HTML element.
You can pass each string as an individual argument to echo:
echo "<p>", $row['info'], "</p>";
This avoids the creation of a new string, uses less memory and runs slightly faster (the improvement speed is not significant unless you do it thousands of times in a loop).
Read about the echo language construct.
Also please note that $row[info] is not correct. The correct way is $row['info']. It is explained in the documentation why.
You need to do something with variable, instead of just saving some data in it in the first loop.
With your current setup first loop with only variable storage will always be faster as operation with IO (input/output) devices are slow that means echo to print output in screen.
But if you add an echo after the variable statement then, loop with only single echo will obviously be faster.

Assigning NULL to a PHP variable doesn't clean the memory

I have read several times that, in order to invoke the garbage collector and actually clean the RAM used by a variable, you have to assign a new value (e.g. NULL) instead of simply unset() it.
This code, however, shows that the memory allocated for the array $a is not cleaned after the NULL assignment.
function build_array()
{
for ($i=0;$i<10000;$i++){
$a[$i]=$i;
}
$i=null;
return $a;
}
echo '<p>'.memory_get_usage(true);
$a = build_array();
echo '<p>'.memory_get_usage(true);
$a = null;
echo '<p>'.memory_get_usage(true);
The output I get is:
262144
1835008
786432
So part of the memory is cleaned, but not all the memory. How can I completely clean the RAM?
You have no way to definitely clear a variable from the memory with PHP.
Its is up to PHP garbage collector to do that when it sees that it should.
Fortunately, PHP garbage collector may not be perfect but it is one of the best features of PHP. If you do things as per the PHP documentation there's no reasons to have problems.
If you have a realistic scenario where it may be a problem, post the scenario here or report it to PHP core team.
Other unset() is the best way to clear vars.
Point is that memory_get_usage(true) shows the memory allocated to your PHP process, not the amount actually in use. System could free unused part once it is required somewhere.
More details on memory_get_usage could be found there
If you run that with memory_get_usage(false), you will see that array was actually gc'd. example

Dump all variables in PHP

There's a memory leak in my script and I couldn't find it after 2 days. I found the loop that is causing the memory leak; each iteration of the loop increases the memory usage. I moved the loop into a function to isolate the variables. At the end of the function, I unsetted every variable created by the function so that get_defined_vars() returns an empty array. Here's what I mean:
function the_loop(){
$var="value";
... // processing, including using a library
unset($var);
print_r(get_defined_vars()); // prints empty array
}
while(true){
the_loop();
echo memory_get_usage()."\n"; // steadily increases until memory limit is reached
}
I'm guessing that some variables defined in the_loop() are still in memory. I tried using XDebug's trace tool, but it didn't help. All it showed was that memory usage increases on average over the long run. I'm looking for a tool that can show me all the values in PHP's memory. I will be able to recognize the variable based on the value. What tool can dump PHP's memory?
As Dragon mentioned unset doesn't instantly free memory.
What's better at freeing memory with PHP: unset() or $var = null
I'd consider re-evaluating the way you're using PHP, it's not designed for long/constant running scripts, the garbage handler simply isn't that great.
If you want to dig further into the executing script I'd suggest checking out some tools like:
https://github.com/jokkedk/webgrind
http://xhprof.io/
http://derickrethans.nl/xdebug-and-tracing-memory-usage.html
Also worth a read: What gc_collect_cycles function is useful for?
Calling unset() does not force garbage collection, so while the reference count should decrease there may be others referencing it. Use xdebug_debug_zval($var) before calling unset to see how many references to its value there actually are.

PHP - Problem with scalar value and memory leak

I am dealing with a very strange situation that has to do with the Warning: Cannot use a scalar value as an array and memory leak.
The script is very simple and I can not figure out the problem.
Code
$variants=array();
if($text)
{
$v=explode(",",$text);
if(is_array($v) && sizeof($v)>0)
{
foreach($v as $i=>$part)
{
$tmp=explode(":",$part);
list($thekey,$thevalue)=$tmp;
//$variants=array();
echo "<div>TYPE==".gettype($variants)."</div>";
echo $variants[$tmp[0]]=$tmp[1];
}
}
}
If I run the code above as stand alone is working fine. But when put it in my framework as small part behave very strange. I got a Warning: Cannot use a scalar value as an array and in order to solve it I added
$variants=array();
on the first line. When running the script the gettype returns ��� the first time and after that return integer.
If i uncomment $variants=array(); just before the gettype, it works. But of course I don't to get the whole array, only the last record return.
I parse my code to find out that the variables I use are declared before I even change all the variable names to stupids but no luck.
Trying to debug and tune the code where times that when running the script instead of see something in the screen the browser download the script instead and some other times I had memory leaks.
Can anyone point where or what to look for, or debug it and solve it?
Problem solved
Before run the code i was calling a function
$obj->draw($$id)
That was causing the problem
The solution
$value=$$id;
$obj->draw($value)
I dont know why this causing the problem.
If anyone has a theory please post it.

Force freeing memory in PHP

In a PHP program, I sequentially read a bunch of files (with file_get_contents), gzdecode them, json_decode the result, analyze the contents, throw most of it away, and store about 1% in an array.
Unfortunately, with each iteration (I traverse over an array containing the filenames), there seems to be some memory lost (according to memory_get_peak_usage, about 2-10 MB each time). I have double- and triple-checked my code; I am not storing unneeded data in the loop (and the needed data hardly exceeds about 10MB overall), but I am frequently rewriting (actually, strings in an array). Apparently, PHP does not free the memory correctly, thus using more and more RAM until it hits the limit.
Is there any way to do a forced garbage collection? Or, at least, to find out where the memory is used?
it has to do with memory fragmentation.
Consider two strings, concatenated to one string. Each original must remain until the output is created. The output is longer than either input.
Therefore, a new allocation must be made to store the result of such a concatenation. The original strings are freed but they are small blocks of memory.
In a case of 'str1' . 'str2' . 'str3' . 'str4' you have several temps being created at each . -- and none of them fit in the space thats been freed up. The strings are likely not laid out in contiguous memory (that is, each string is, but the various strings are not laid end to end) due to other uses of the memory. So freeing the string creates a problem because the space can't be reused effectively. So you grow with each tmp you create. And you don't re-use anything, ever.
Using the array based implode, you create only 1 output -- exactly the length you require. Performing only 1 additional allocation. So its much more memory efficient and it doesn't suffer from the concatenation fragmentation. Same is true of python. If you need to concatenate strings, more than 1 concatenation should always be array based:
''.join(['str1','str2','str3'])
in python
implode('', array('str1', 'str2', 'str3'))
in PHP
sprintf equivalents are also fine.
The memory reported by memory_get_peak_usage is basically always the "last" bit of memory in the virtual map it had to use. So since its always growing, it reports rapid growth. As each allocation falls "at the end" of the currently used memory block.
In PHP >= 5.3.0, you can call gc_collect_cycles() to force a GC pass.
Note: You need to have zend.enable_gc enabled in your php.ini enabled, or call gc_enable() to activate the circular reference collector.
Found the solution: it was a string concatenation. I was generating the input line by line by concatenating some variables (the output is a CSV file). However, PHP seems not to free the memory used for the old copy of the string, thus effectively clobbering RAM with unused data. Switching to an array-based approach (and imploding it with commas just before fputs-ing it to the outfile) circumvented this behavior.
For some reason - not obvious to me - PHP reported the increased memory usage during json_decode calls, which mislead me to the assumption that the json_decode function was the problem.
There's a way.
I had this problem one day. I was writing from a db query into csv files - always allocated one $row, then reassigned it in the next step. Kept running out of memory. Unsetting $row didn't help; putting an 5MB string into $row first (to avoid fragmentation) didn't help; creating an array of $row-s (loading many rows into it + unsetting the whole thing in every 5000th step) didn't help. But it was not the end, to quote a classic.
When I made a separate function that opened the file, transferred 100.000 lines (just enough not to eat up the whole memory) and closed the file, THEN I made subsequent calls to this function (appending to the existing file), I found that for every function exit, PHP removed the garbage. It was a local-variable-space thing.
TL;DR
When a function exits, it frees all local variables.
If you do the job in smaller portions, like 0 to 1000 in the first function call, then 1001 to 2000 and so on, then every time the function returns, your memory will be regained. Garbage collection is very likely to happen on return from a function. (If it's a relatively slow function eating a lot of memory, we can safely assume it always happens.)
Side note: for reference-passed variables it will obviously not work; a function can only free its inside variables that would be lost anyway on return.
I hope this saves your day as it saved mine!
I've found that PHP's internal memory manager is most-likely to be invoked upon completion of a function. Knowing that, I've refactored code in a loop like so:
while (condition) {
// do
// cool
// stuff
}
to
while (condition) {
do_cool_stuff();
}
function do_cool_stuff() {
// do
// cool
// stuff
}
EDIT
I ran this quick benchmark and did not see an increase in memory usage. This leads me to believe the leak is not in json_decode()
for($x=0;$x<10000000;$x++)
{
do_something_cool();
}
function do_something_cool() {
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$result = json_decode($json);
echo memory_get_peak_usage() . PHP_EOL;
}
I was going to say that I wouldn't necessarily expect gc_collect_cycles() to solve the problem - since presumably the files are no longer mapped to zvars. But did you check that gc_enable was called before loading any files?
I've noticed that PHP seems to gobble up memory when doing includes - much more than is required for the source and the tokenized file - this may be a similar problem. I'm not saying that this is a bug though.
I believe one workaround would be not to use file_get_contents but rather fopen()....fgets()...fclose() rather than mapping the whole file into memory in one go. But you'd need to try it to confirm.
HTH
C.
Call memory_get_peak_usage() after each statement, and ensure you unset() everything you can. If you are iterating with foreach(), use a referenced variable to avoid making a copy of the original (foreach()).
foreach( $x as &$y)
If PHP is actually leaking memory a forced garbage collection won't make any difference.
There's a good article on PHP memory leaks and their detection at IBM
There recently was a similar issue with System_Daemon. Today I isolated my problem to file_get_contents.
Could you try using fread instead? I think this may solve your problem.
If it does, it's probably time to do a bugreport over at PHP.

Categories