Programming Languages PHP Subjective
Sep 23, 2025

Analyze this PHP code and explain the memory implications. What are the potential issues and how would you optimize it?

Detailed Explanation

Code Analysis:

function processLargeDataset($filename) {
    $data = file_get_contents($filename); // 100MB file
    $lines = explode("\n", $data);
    $results = [];
    
    foreach($lines as $line) {
        $processed = expensive_operation($line);
        $results[] = $processed;
    }
    
    return $results;
}

Memory Issues:

  • Memory Spike: file_get_contents() loads entire file into memory
  • Double Memory Usage: explode() creates another copy of data
  • Array Growth: $results array grows continuously
  • Peak Usage: Could reach 300MB+ for 100MB file

Optimized Solution:

function processLargeDatasetOptimized($filename): Generator {
    $handle = fopen($filename, "r");
    if (!$handle) throw new Exception("Cannot open file");
    
    try {
        while (($line = fgets($handle)) !== false) {
            yield expensive_operation(trim($line));
        }
    } finally {
        fclose($handle);
    }
}

// Usage with memory control
foreach(processLargeDatasetOptimized($filename) as $result) {
    // Process one result at a time
    // Memory usage remains constant
}

Benefits: Constant memory usage, lazy evaluation, better performance for large datasets.

Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback