0Pricing
PHP Academy · Lesson

Memory Management and Performance Tips

Free memory early, avoid large array copies, and use generators for big datasets.

Memory Management and Performance Tips is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

PHP Memory Management

PHP uses reference counting with a cycle collector for garbage collection. Each request starts with a fresh heap — long-running processes (workers, Horizon) can accumulate memory leaks.

memory_limit

Set an appropriate memory limit in php.ini. Exceeding it raises a fatal error.

# php.ini:
memory_limit = 256M

// Check at runtime:
echo memory_get_usage(true)   / 1024 / 1024 . " MB";
echo memory_get_peak_usage(true) / 1024 / 1024 . " MB peak";

Unset Large Variables

Free memory explicitly when large arrays or objects are no longer needed within a long function.

<?php
$data = loadLargeDataset();
processData($data);
unset($data); // free immediately, do not wait for end of scope
gc_collect_cycles(); // force garbage collection if circular references

Generators for Large Datasets

Use generators to process large files or query results one row at a time without loading everything into memory.

<?php
function readCsvLines(string $file): Generator {
    $fh = fopen($file, "r");
    while (($line = fgetcsv($fh)) !== false) {
        yield $line;
    }
    fclose($fh);
}

foreach (readCsvLines("large.csv") as $row) {
    importRow($row);
}

Avoid Copying Large Arrays

PHP uses copy-on-write for arrays. Assigning an array to a variable does not copy it until one of them is modified. Pass large arrays by reference when mutation is needed.

<?php
function processArray(array &$data): void {
    // & avoids a copy when the parameter is modified
}

String Concatenation in Loops

Building a string by concatenating in a loop is inefficient for very large strings. Use an array and implode().

<?php
// Slow for large N:
$str = "";
foreach ($items as $item) $str .= $item->format()."\n";

// Faster:
$parts = [];
foreach ($items as $item) $parts[] = $item->format();
$str = implode("\n", $parts);

Caching Object Creation

Instantiating objects (especially with constructor logic) in tight loops is expensive. Cache instances or use flyweight objects where possible.

Avoid Repeated Function Calls

Move constant function calls out of loops when the result does not change per iteration.

<?php
// Slow:
for ($i = 0; $i < count($items); $i++) { ... }

// Fast (count() called once):
$n = count($items);
for ($i = 0; $i < $n; $i++) { ... }

PHP-FPM Worker Tuning

Configure PHP-FPM worker counts based on available memory and expected concurrency. A rough rule: workers = RAM / (average worker memory usage).

OPcache and Preloading

Enable OPcache (covered in the previous lesson) and preload frequently-used framework classes. This eliminates per-request parse and compile overhead.

Profiling First

Always profile before optimising. Micro-optimisations applied to non-bottleneck code waste time and reduce readability. Use Xdebug or Blackfire to find the actual hot path.

Summary

Use generators for large datasets. Unset variables when done. Avoid copies of large arrays. Move constant calls outside loops. Profile with Xdebug to find actual bottlenecks before optimising.

Quick Check

What is the main benefit of PHP generators for large datasets?

Frequently asked questions

Is the “Memory Management and Performance Tips” lesson free?

Yes — the full text of “Memory Management and Performance Tips” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Memory Management and Performance Tips”?

Free memory early, avoid large array copies, and use generators for big datasets. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Memory Management and Performance Tips” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Profiling PHP with Xdebug
  2. OPcache: Bytecode Caching
  3. Optimizing Database Queries
  4. Memory Management and Performance Tips
← Back to PHP Academy