As soon as I arrived at the company this morning, some colleagues in the company group reported that some planned tasks had problems. So I went to the log with an inquisitive mind. There is an interesting problem that PHP memory overflow causes script execution to fail. Let’s find out!
1. View the Log of the scheduled task
As you can see from the error message literal, 134217728 bytes allowed memory has been used up, and 12961640 bytes more memory is being attempted.
You have used up the memory allocated to you (the current script) and you want to ask the system for memory. The system wants to say to you,
The landlord also has no surplus grain (to borrow ge You uncle’s words)
1. Simulate a crime scene
- Create a new mem_friends.php file and copy it to a 2.4m log file for testing purposes
- Write a simple script to recreate the scene and deliberately allocate 1 MB of memory to read 2.4 MB of logs
- Execute the script and re-enact the crime scene
1. Analyze the cause of the “accident”
The script reads a large amount of data (either a read file or a read database) at one time as shown in the following figure: Count down the water (log file data) into the cup (memory allocated to the current script), and the cup (memory) is not enoughCopy the code
2. Solutions
A. 'ini_set('memory_limit','100M'); `Copy the code
B. Pour the batch of water into the cup.
Look at the results
Piecewise reading can also solve the problem
Other optimization schemes
- The use of static variables should be minimized, and references (&) should be considered when data reuse is required.
- Close the connection as soon as the database operation is complete;
- Call the destruct function (__destruct()) immediately after an object is used.
- Used variables are destroyed (unset()) immediately
- You can use the memory_get_usage() function to get the current occupied memory and adjust the program based on the memory currently in use
- The unset() function frees memory only if the value of the variable takes up more than 256 bytes. (Determined by the PHP kernel’s GC garbage collection mechanism)
- Memory is freed only after all variables pointing to the variable, such as reference variables, have been destroyed
(The underlying PHP variable implementation is a _zval_struct structure,is_ref__gc indicates reference counting,is_ref__gc indicates whether it is a reference or not)