Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Memory Leaks in Long Running Scripts | Memory Profiling and Optimization
Practice
Projects
Quizzes & Challenges
Quizze
Challenges
/
PHP Memory Management

bookMemory Leaks in Long Running Scripts

Long running PHP scripts, such as daemons, background workers, or web crawlers, are especially prone to memory leaks. In PHP, a memory leak occurs when a script continually allocates memory without releasing it, causing the process's memory usage to grow over time. This can eventually exhaust system resources, leading to degraded performance or crashes. Unlike short-lived scripts that terminate and free all memory at the end of execution, long running scripts persist in memory, so even small leaks can accumulate and become significant.

Several factors contribute to memory leaks in PHP long running scripts:

  • Persistently growing arrays or collections that are never cleared;
  • Global variables or static variables that accumulate data without being reset;
  • Objects with circular references that the garbage collector cannot clean up if not triggered or if certain extensions interfere;
  • Resources such as file handles, database connections, or cURL handles that are not explicitly closed;
  • Unintentional retention of large data structures by closures or callbacks.

To prevent memory leaks in these scenarios, you should adopt several strategies:

  • Unset variables, arrays, or objects that are no longer needed, especially inside loops;
  • Explicitly close or release resources when done with them;
  • Use functions like gc_collect_cycles() to force garbage collection in scripts that process large numbers of objects or data;
  • Avoid unnecessary global or static variables that retain references to large data;
  • Monitor memory usage during script execution and log or act if it grows unexpectedly.

By following these practices, you can ensure that your long running PHP scripts remain efficient and stable over time.

memory_leak_demo.php

memory_leak_demo.php

copy
12345678910111213141516171819202122232425262728293031323334
<?php // memory_leak_demo.php // Simulate a long running process that processes data in a loop echo "Starting memory leak simulation...\n"; // Uncomment one of the following blocks to see the difference // --- Block 1: Without unsetting variables (Memory Leak) --- // $data = []; // for ($i = 0; $i < 100000; $i++) { // $data[] = str_repeat("A", 1024); // 1KB string // if ($i % 10000 === 0) { // echo "Iteration $i, Memory usage: " . memory_get_usage(true) . " bytes\n"; // // sleep(1); // Uncomment to slow down loop for observation // } // } // echo "Final memory usage (leak): " . memory_get_usage(true) . " bytes\n"; // --- Block 2: With unsetting variables (No Memory Leak) --- for ($i = 0; $i < 100000; $i++) { $temp = str_repeat("A", 1024); // 1KB string // Process $temp (simulate work) unset($temp); // Explicitly free memory if ($i % 10000 === 0) { echo "Iteration $i, Memory usage: " . memory_get_usage(true) . " bytes\n"; // sleep(1); // Uncomment to slow down loop for observation } } echo "Final memory usage (no leak): " . memory_get_usage(true) . " bytes\n"; // In Block 1, memory usage increases continually because the array grows and is never cleared. // In Block 2, memory usage remains stable because variables are unset and not accumulated. ?>
question mark

Which of the following practices can help prevent memory leaks in long running PHP scripts?

Select all correct answers

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

bookMemory Leaks in Long Running Scripts

Swipe um das Menü anzuzeigen

Long running PHP scripts, such as daemons, background workers, or web crawlers, are especially prone to memory leaks. In PHP, a memory leak occurs when a script continually allocates memory without releasing it, causing the process's memory usage to grow over time. This can eventually exhaust system resources, leading to degraded performance or crashes. Unlike short-lived scripts that terminate and free all memory at the end of execution, long running scripts persist in memory, so even small leaks can accumulate and become significant.

Several factors contribute to memory leaks in PHP long running scripts:

  • Persistently growing arrays or collections that are never cleared;
  • Global variables or static variables that accumulate data without being reset;
  • Objects with circular references that the garbage collector cannot clean up if not triggered or if certain extensions interfere;
  • Resources such as file handles, database connections, or cURL handles that are not explicitly closed;
  • Unintentional retention of large data structures by closures or callbacks.

To prevent memory leaks in these scenarios, you should adopt several strategies:

  • Unset variables, arrays, or objects that are no longer needed, especially inside loops;
  • Explicitly close or release resources when done with them;
  • Use functions like gc_collect_cycles() to force garbage collection in scripts that process large numbers of objects or data;
  • Avoid unnecessary global or static variables that retain references to large data;
  • Monitor memory usage during script execution and log or act if it grows unexpectedly.

By following these practices, you can ensure that your long running PHP scripts remain efficient and stable over time.

memory_leak_demo.php

memory_leak_demo.php

copy
12345678910111213141516171819202122232425262728293031323334
<?php // memory_leak_demo.php // Simulate a long running process that processes data in a loop echo "Starting memory leak simulation...\n"; // Uncomment one of the following blocks to see the difference // --- Block 1: Without unsetting variables (Memory Leak) --- // $data = []; // for ($i = 0; $i < 100000; $i++) { // $data[] = str_repeat("A", 1024); // 1KB string // if ($i % 10000 === 0) { // echo "Iteration $i, Memory usage: " . memory_get_usage(true) . " bytes\n"; // // sleep(1); // Uncomment to slow down loop for observation // } // } // echo "Final memory usage (leak): " . memory_get_usage(true) . " bytes\n"; // --- Block 2: With unsetting variables (No Memory Leak) --- for ($i = 0; $i < 100000; $i++) { $temp = str_repeat("A", 1024); // 1KB string // Process $temp (simulate work) unset($temp); // Explicitly free memory if ($i % 10000 === 0) { echo "Iteration $i, Memory usage: " . memory_get_usage(true) . " bytes\n"; // sleep(1); // Uncomment to slow down loop for observation } } echo "Final memory usage (no leak): " . memory_get_usage(true) . " bytes\n"; // In Block 1, memory usage increases continually because the array grows and is never cleared. // In Block 2, memory usage remains stable because variables are unset and not accumulated. ?>
question mark

Which of the following practices can help prevent memory leaks in long running PHP scripts?

Select all correct answers

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 2
some-alt