__autoload() 和 include/require 哪个更有效?
嵌套 if 语句中的 __autoload
或 include
哪个执行时间更快? 两者之间哪个更不容易出错?
Which has faster execution time: __autoload
or include
inside nested if statements?
Which is less error prone between the two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
spl_autoload_register
(而不是__autoload
) 应该是更强大的选项:它允许您编写比include
语句更灵活的代码,并且您可以将所有内容集中起来。关于性能,恕我直言,讨论它是没有意义的,除非您已经测量到页面加载时间的很大一部分花费在加载包含上。即使这是真的,您也应该使用 PHP 操作码缓存来加速您的应用程序,而不是试图通过在
include
和自动加载之间切换来获取边际收益。spl_autoload_register
(instead of__autoload
) should be the more robust option: it allows you to write code much more flexible than what is possible withinclude
statements, and you can keep everything centralized.Regarding performance, IMHO it's not meaningful to discuss it unless you have measured that a significant percentage of your page load times are spent on loading includes. Even if this is true, you should use a PHP opcode cache to speed your application up instead of trying to extract marginal benefits from switching between
include
and autoloading.只需使用 include/require 即可获得可读、可维护且标准的代码。这比您可能节省的 0.001 秒重要得多。
顺便问一下,您真的确定您的 PHP 脚本需要极高的性能吗?包含真的是瓶颈吗?
Just use include/require and get readable, maintainable and standard code. This is much more important than the 0.001 second you might save.
By the way, are you really sure you need extreme performance of your PHP scripts? Is the including really the bottleneck?
无论您使用
include
/require
还是__autoload
/spl_autoload
大部分时间都会(无论如何在大多数情况下)花费在加载、解析和编译所包含的源代码上。相比之下,执行这几行 autolaoder 函数几乎不重要。Whether you're using
include
/require
or__autoload
/spl_autoload
most time will be (in most cases anyway) spent on loading, parsing and compiling the included source code. Execution of those few lines of autolaoder function(s) will hardly matter in comparison.看一下: http://framework.zend.com/manual/en/ Performance.classloading.html
require_once
实际上是一个昂贵的操作(检查文件是否已经加载)。 自动加载将提高您的性能。正如 Jon 建议的那样,您可能想尝试
spl_autoload_register
而不是__autoload
(请参阅他的答案)。但是,请注意,这是一个小的优化,我只是为您的问题提供答案。
编辑:首先,我写的与我现在建议的相反,所以我更新了我的答案。
Have a look at: http://framework.zend.com/manual/en/performance.classloading.html
require_once
is actually an expensive operation (checking if the file has already be loaded). Autoloading will improve your performances.As Jon suggested, you might want to try
spl_autoload_register
rather than__autoload
(see his answer).However, be aware that this is a small optimization, I'm just providing your question an answer.
Edit: at first, I wrote the opposite of what I suggest now, so I updated my answer.