为什么require_once如此糟糕?

为什么require_once如此糟糕?

我读到的关于更好的PHP编码实践的一切都在说不要require_once因为速度而使用。

为什么是这样?

做同样事情的正确/更好的方法是什么require_once?如果重要,我使用的是PHP5。


手掌心
浏览 637回答 3
3回答

凤凰求蛊

require_once并且include_once都要求系统记录已经包含/需要的内容。每次*_once通话都意味着检查该日志。所以肯定有一些额外的工作要做,但足以损害整个应用程序的速度?......我真的很怀疑......除非你真的使用旧硬件或者做很多事情。如果你正在做的成千上万*_once,你可以做的更轻的时尚自己的工作。对于简单的应用程序,只是确保你只包括一次应该足够了,但如果你仍然得到重新定义错误,你可以是这样的:if (!defined('MyIncludeName')) {&nbsp; &nbsp; require('MyIncludeName');&nbsp; &nbsp; define('MyIncludeName', 1);}我个人会坚持这些*_once陈述,但是对于愚蠢的万通基准,你可以看到两者之间的差异:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; php&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hhvmif defined&nbsp; &nbsp; &nbsp; 0.18587779998779&nbsp; &nbsp; &nbsp;0.046600103378296require_once&nbsp; &nbsp; 1.2219581604004&nbsp; &nbsp; &nbsp; 3.290859937667810-100倍慢,require_once而且好奇的require_once是看起来比较慢hhvm。同样,如果您运行了*_once数千次,这只与您的代码相关。<?php // test.php$LIMIT = 1000000;$start = microtime(true);for ($i=0; $i<$LIMIT; $i++)&nbsp; &nbsp; if (!defined('include.php')) {&nbsp; &nbsp; &nbsp; &nbsp; require('include.php');&nbsp; &nbsp; &nbsp; &nbsp; define('include.php', 1);&nbsp; &nbsp; }$mid = microtime(true);for ($i=0; $i<$LIMIT; $i++)&nbsp; &nbsp; 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.
打开App,查看更多内容
随时随地看视频慕课网APP