我们知道,在php中使用require_once/include_once虽然方便,但是代价昂贵,据测试数据来看,require_once比require慢3-4倍,所以在php开发中,我们应该尽量使用require/include。
列一下俺常用的避免require/include的方法。
使用__autoload
php5可以使用__autoload来避免require,用的好的话,代码里头甚至看不到几个require,实在是安逸啊。测试结果表明,使用__autoload之后的new Foo; 比require_once ‘foo.php’; new Foo; 大概要快3倍左右。
补充:为了避免autoload冲突,可以考虑使用spl_autoload_register(PHP 5 >= 5.1.2)来改变魔术函数__autoload的行为。
使用defined检测是否载入过
在代码开头使用defined检测是否定义过对应的常量,如果有的话,直接return。
if(!defined('_MYCLASS_'))
return;
define('_MYCLASS_', 1);
class MyClass { ... }
?>
测试了一下,defined的性能也不是太好…
require前检查
用class_exists或者function_exists检查一下,确认没有载入过再出手,至少比require_once能快上3倍。php4也可以用上。
class_exists('myClass') or require('/path/to/myClass.class.php');

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
