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

查看:33
本文介绍了为什么 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?

...我真的很怀疑...除非您使用真的旧硬件或很多.

... 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	%s
require_once	%s
", $mid-$start, $end-$mid);

<小时>

<?php // include.php

// do nothing.

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

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