— Original article reproduced please indicate the source

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. First, I looked at the Log of the scheduled task





    log_error.png

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)





geyou.png

  1. Simulate a crime scene.
    • Create a new mem_friends.php file and copy it to a 2.4m log file for testing purposes





      log_size.png

    • Write a simple script to recreate the scene and deliberately allocate 1 MB of memory to read 2.4 MB of logs





      test_mem_1.png

    • Execute the script and re-enact the crime scene





      test_run_res.png

  1. Analyzing the cause of the “accident” The script reads a large amount of data (either the read file or the read database) at one time as shown in the following figure: Counting down water (log file data) into the cup (memory allocated to the current script), the cup (memory) is insufficient





    water_overflow.jpg

  2. Solution A. Change the size of the cup to a larger one (increase the memory allocated to the script) : ini_set(‘memory_limit’,’100M’);





    new_1.png

    B. Pour the batch of water into the cup.





code_1.png

Look at the results





run_res_new.png

Piecewise reading can also solve the problem

  1. 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)
    • The underlying implementation of a PHP variable is a _zval_struct structure. Refcount_gc indicates the reference count. Is_ref__gc indicates whether it is a reference.

Hasty written, improper place, inevitable, still hope reader, add correction