php include文件想必大家已经是非常的熟悉了,目前流行是用php框架,大部分的框架在运行时需要include大量的php文件,那么,php代码中include大量的文件是否存在性能问题呢?如果有,我们应该如何避免及优化我们的php程序呢?下面,我讲对这个两个问题做出解答:
首先我们来看php官方手册中对include的文件搜索原则的描述:
Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries , current working directory is /www/ , you includedinclude/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/ . If filename begins with ./ or ../ , it is looked only in the current working directory.
寻找包含文件的顺序先是在当前工作目录的相对的 include_path 下寻找,然后是当前运行脚本所在目录相对的 include_path 下寻找。例如 include_path 是 .,当前工作目录是 /www/,脚本中要 include 一个 include/a.php 并且在该文件中有一句 include "b.php",则寻找 b.php 的顺序先是 /www/,然后是 /www/include/。如果文件名以 ./ 或者 ../ 开始,则只在当前工作目录相对的 include_path 下寻找。
下面,我们来做一些测试,看看include后面文件路径的不同写法include_path的配置 和带来的程序性能差异
测试环境:ubuntu 10.10 php 5.3.4
首先,我们测试无路径标示的include方式,下面是代码:
平均成绩:9.02秒
然后我们测试设置大量include_path,代码如下
平均成绩:10.35秒
然后我们再测试 ./ 开头的相对路径
平均成绩:8.96秒
然后我们再来测试大量的include_path和 ./ 开头的相对路径,代码如下
平均成绩:9.07秒
最后,我们测试以绝对路径的方式来include文件
平均成绩: 8.14 秒
下面是测试记录表:(点击放大)
结论:
显然include 后面路径的格式和php的include path 对程序性能都是存在影响的,include 性能从慢到快的排序是
include 'a.php' < include './a.php' < include '/fullpath/a.php
在代码中,使用绝对路径include文件是最好的选择,因为这样php内核就直接通过路径去载入文件而不用去include path逐个搜索文件。
所以我们最好在项目的公用文件中定义一个项目根目录绝对路径的常量,然后所有的include的路径前都带上这个常量,这样项目中所有的include使用的都是绝对路径,既提高程序性能,也减少了相对路径带来的烦恼。
参考代码(来自emlog):
define('EMLOG_ROOT', dirname(__FILE__));
include EMLOG_ROOT . '/config.php';
如果你的项目中已经大量使用include 'test.php' 这样格式的相对路径且不好大量修改,那么请尽量减少php include path中的路径以提高一定的include性能。因为include path中的路径越少,php搜索文件的时间也越少。