Implement Lazy Loading for Performance Optimization

Implement Lazy Loading for Performance Optimization

Lazy loading is a design pattern that defers the initialization of an object until it's needed. This can significantly improve performance, especially in applications with complex object graphs.

class ExpensiveResource
{
    private $data;

    public function getData()
    {
        if ($this->data === null) {
            $this->data = $this->loadExpensiveData();
        }
        return $this->data;
    }

    private function loadExpensiveData()
    {
        // Simulate expensive operation
        sleep(2);
        return "Expensive data loaded";
    }
}

$resource = new ExpensiveResource();
// Data is not loaded yet

echo $resource->getData(); // Now the data is loaded

echo $resource->getData(); // Data is returned from cache, no expensive operation

This pattern is especially useful in scenarios where you have expensive-to-create objects that might not always be used in a given request cycle.

← Back to Tips List