Home  >  Article  >  Backend Development  >  Troubleshooting to prevent memory overflow in PHP process

Troubleshooting to prevent memory overflow in PHP process

藏色散人
藏色散人forward
2020-06-24 13:42:112396browse

The memory size of the PHP process can be set. The default is in the configuration file memory_limit=128M

It can also be set dynamically in the program ini_set('memory_limit', '1024M');This will set it to 1G. However, this setting is generally not done as it will affect other services of the machine. Sometimes you can check the code. Many times, memory overflow occurs because PHP variables are not released in time, or when traversing a relatively large array.

1. Troubleshooting

memory_get_usage() PHP has this system function to get how much memory space is used by the current process. The return is the byte unit round(memory_get_usage()/1024/1024, 2).'MB', which can be converted into MB.

to track the code execution process memory changes.

2. Common memory overflow cases

Traverse a large array and modify some values ​​of the array, resulting in a copy of the array during the traversal process.

The characteristic of PHP variables is "copy on write".

When it comes to $arr array assignment, it will split and generate a new HashTable structure, causing the memory usage to change instantly. Big

3. Traverse and assign other variables

$arr = range(0, 599999);
echo &#39;foreach前内存:&#39;.round(memory_get_usage()/1024/1024, 2).&#39;MB&#39;, &#39;<br/>&#39;;
foreach($arr as $key => $item) {
    $arr[$key] = $item + 1;
    if($item % 100000 == 0) {
        echo &#39;foreach中内存:&#39;.round(memory_get_usage()/1024/1024, 2).&#39;MB&#39;, &#39;<br/>&#39;;
    }
}
echo &#39;foreach后内存:&#39;.round(memory_get_usage()/1024/1024, 2).&#39;MB&#39;, &#39;<br/>&#39;;

//输出
/*
foreach前内存:49.9MB
foreach中内存:81.36MB
foreach中内存:84.42MB
foreach中内存:87.47MB
foreach中内存:90.52MB
foreach中内存:93.57MB
foreach中内存:96.62MB
foreach后内存:49.9MB
*/

The solution is to use reference traversal

$arr = range(0, 599999);
echo &#39;foreach前内存:&#39;.round(memory_get_usage()/1024/1024, 2).&#39;MB&#39;, &#39;<br/>&#39;;

foreach($arr as $key => &$item) {
    $arr[$key] = $item + 1;
    if($item % 100000 == 0) {
        echo &#39;foreach中内存:&#39;.round(memory_get_usage()/1024/1024, 2).&#39;MB&#39;, &#39;<br/>&#39;;
    }
}unset($key);unset($item);

After the traversal is completed, remember to unset($key);unset($item); Because $item is a reference to the last element of the array, if you modify this variable later, it will be directly modified to the array.

Recommended: "PHP Video Tutorial"

The above is the detailed content of Troubleshooting to prevent memory overflow in PHP process. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete