If it is useful to you, remember to pay attention, more dry goods.
As soon as I arrived at the company this morning, a colleague reported in the company group that there was a problem with a planned task. I went to check the log with a deep-rooted heart. I found a very interesting problem, the PHP memory overflow caused the script execution to fail. Then let's find out together!
First check the Log of the scheduled task
From the literal meaning of the error message, it can be seen that the allowed 134217728 bytes of memory has been used up, and an attempt is made to allocate 12961640 bytes
of memory.
You have run out of memory allocated to you (the current script), and you still want to ask the system for memory. The system wants to say to you at this time:
The landlord's house has no surplus food (to borrow a sentence from Uncle Ge You)
Simulate a "criminal scene"
Create a new mem_exhausted.php file and copy a 2.4M log file for testing
Write a simple script to reproduce the "criminal scene" and deliberately allocate 1M of memory to read 2.4M of log
Execute the script and reproduce the "criminal scene"
Analysis of "accident" causes
The script reads a large amount of data at once (maybe a file read, a database may be read)
As shown below: Count down the water (data in the log file) into the cup (memory allocated to the current script), the cup capacity (memory) is not enough
solution
a. Since the cup is small, change to a larger cup (increase the memory allocated to the script) to cure the symptoms but not the root cause:
ini_set('memory_limit','100M');
b. Pour the water batches into the cup (loop, read data in sections, and limit if you read the database)
see the results
Segmented reading can also solve the problem
Other optimization solutions
-
The use of static variables should be minimized, and references (&) should be considered when data reuse is required.
After the database operation is completed, the connection should be closed immediately;
When an object is used up, call the destructor (__destruct()) in time
The used variables are destroyed in time (unset())
You can use the memory_get_usage() function to get the currently occupied memory to adjust the program according to the currently used memory
The unset() function only frees the memory space when the variable value occupies more than 256 bytes of memory space. (determined by the gc garbage collection mechanism of the PHP kernel)
The memory will only be released when all variables pointing to the variable (such as reference variables) are destroyed
(The underlying implementation of PHP variables is a _zval_struct structure, is_ref__gc indicates the reference count is_ref__gc indicates whether it is a reference)
Source: https://www.cnblogs.com/gaohj/p/6727069.html?utm_source=tuicool&utm_medium=referral