为什么require_once不好用? [英] Why is require_once so bad to use?

查看:147
本文介绍了为什么require_once不好用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所读到的有关更好的PHP编码实践的所有内容都一直在说不要因为速度而不使用require_once.

Everything I read about better PHP coding practices keeps saying don't use require_once because of speed.

这是为什么?

做与require_once相同的事情的正确/更好的方法是什么?如果有关系,我正在使用PHP  5.

What is the proper/better way to do the same thing as require_once? If it matters, I'm using PHP 5.

推荐答案

require_onceinclude_once都要求系统保留已包含/需要的内容的日志.每个*_once调用都意味着检查该日志.因此,肯定有一些额外的工作正在做,但足以损害整个应用程序的速度?

require_once and include_once both require that the system keeps a log of what's already been included/required. Every *_once call means checking that log. So there's definitely some extra work being done there but enough to detriment the speed of the whole app?

...我真的对此表示怀疑...除非您使用的是真正的旧硬件或在 lot 上进行操作.

... I really doubt it... Not unless you're on really old hardware or doing it a lot.

如果您正在做数千个*_once,则可以以更轻松的方式自己完成工作.对于简单的应用程序,只需确保只包含一次应该就足够了,但是如果仍然遇到重新定义的错误,则可以这样:

If you are doing thousands of *_once, you could do the work yourself in a lighter fashion. For simple apps, just making sure you've only included it once should suffice but if you're still getting redefine errors, you could something like this:

if (!defined('MyIncludeName')) {
    require('MyIncludeName');
    define('MyIncludeName', 1);
}

我个人会坚持使用*_once语句,但是在愚蠢的百万次通过基准测试中,您会看到两者之间的区别:

I'll personally stick with the *_once statements but on silly million-pass benchmark, you can see a difference between the two:

                php                  hhvm
if defined      0.18587779998779     0.046600103378296
require_once    1.2219581604004      3.2908599376678

使用require_once慢10-100倍,奇怪的是require_oncehhvm中似乎慢.同样,这仅在您运行*_once数千次的情况下才与您的代码相关.

10-100× slower with require_once and it's curious that require_once is seemingly slower in hhvm. Again, this is only relevant to your code if you're running *_once thousands of times.

<?php // test.php

$LIMIT = 1000000;

$start = microtime(true);

for ($i=0; $i<$LIMIT; $i++)
    if (!defined('include.php')) {
        require('include.php');
        define('include.php', 1);
    }

$mid = microtime(true);

for ($i=0; $i<$LIMIT; $i++)
    require_once('include.php');

$end = microtime(true);

printf("if defined\t%s\nrequire_once\t%s\n", $mid-$start, $end-$mid);


<?php // include.php

// do nothing.

这篇关于为什么require_once不好用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆