延迟加载?是不是最好避免呢?

发布于 2024-10-10 01:54:10 字数 98 浏览 1 评论 0原文

我刚刚读到“延迟加载”设计模式。

过度使用延迟加载来加载所有类并完全忘记 include(..) 是否可以?
这种方法有什么缺点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫九 2024-10-17 01:54:10

关于自动加载的几点:

  1. 您将看到良好的性能
    通过使用自动加载进行改进
    与总是包括你所有的
    一直有文件
    (尤其是文件数量
    变得越来越大)。

  2. 实现自动加载时,是
    更好用
    spl_autoload_register()
    __autoload().

尽管很多时候,当人们谈论 PHP 中的延迟加载时,他们谈论的是类似以下内容:

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

然后,您仅在实际需要使用属性时才加载该属性,而不是每次实例化该对象时都加载该属性,这可能会产生潜在的问题。一些好的好处。

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.

若能看破又如何 2024-10-17 01:54:10

惰性加载器的好处之一是它只加载脚本在执行过程中实际需要的类文件,从而可能节省内存;否则,您可能会包含所有类文件,无论是否需要它们。根据您的脚本,这可能会产生很大的不同。

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.

櫻之舞 2024-10-17 01:54:10

可以使用显式包含,或者让 __autoload() 为您找到您的类。无论哪种方式。

不过,我不建议混合使用这两种策略。 include 行是不必要的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文