Shoe
Shoe

Reputation: 76280

Lazy loading? Is it better to avoid it?

I just read about the "lazy loading" design pattern.

Is it ok to overuse lazy loading to load all classes and forget about include(..) entirely?
What are the cons of this approach?

Upvotes: 7

Views: 2754

Answers (3)

mfonda
mfonda

Reputation: 8003

A couple points on autoloading:

  1. You will see a nice performance improvement by using autoloading versus always including all of your files all the time (especially as the number of files grows larger and larger).

  2. When implementing autoloading, it is better to use spl_autoload_register() than __autoload().

Although a lot of times when people talk about lazy loading in PHP, they are talking about something like the following:

class Foo {
    protected $bar = null;
    
    public function getBar() {
        if ($this->bar == null) {
            $this->bar = ExpensiveOperation();
        }
        return $this->bar;
    }
}

Then you only load a property when it actually needs to be used, and not every time you instantiate the object, which can potentially have some good benefits.

Upvotes: 8

Mark Baker
Mark Baker

Reputation: 212452

One benefit of a lazy loader is that it only loads the class files that are actually needed by the script during the course of its execution, potentially saving memory; when otherwise you might include all class files, whether they are needed or not. Depending on your scripts, this can make quite a difference.

Upvotes: 3

Borealid
Borealid

Reputation: 98509

It is fine to use explicit includes, or to have __autoload() find your classes for you. Either way.

I wouldn't recommend mixing the two strategies, though. The include lines would be unnecessary.

Upvotes: 2

Related Questions