最近在做云平台的初步代码架构时,遇到一个常量定义速度比较的问题,故做一下比较。
PHP的APC扩展,在PHP手册里面有下面一段描述:
 
define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition.
 
意思是PHP的define函数比较慢,在开启了apc的PHP环境中,使用apc的常量定义方式比define要快很多。
apc常量定义使用的是apc_define_constants()和apc_load_constants() 这对函数。
这里准备了两段程序,分别测试其运行时间来看其分别:
 
define函数的代码:
 
  1. <?php  
  2. $stime=microtime(true); 
  3.   
  4. define('TMP_PATH''/tmp'); 
  5. // ...其他定义,共20个 
  6.   
  7. echo API_MAIL; 
  8. echo ''
  9.   
  10. $etime=microtime(true); 
  11. echo $etime-$stime
  12. ?> 
 
 
apc的常量定义代码:
 
 
  1. <?php 
  2. $stime=microtime(true); 
  3. if(!apc_load_constants('API')){ apc_define_constants('API'array'TMP_PATH' =--> '/tmp'
  4. // ...其他定义,共20个 
  5. )); 
  6.   
  7. echo API_MAIL; 
  8. echo ''
  9.  
  10. $etime=microtime(true); 
  11. echo $etime-$stime
  12. ?> 
 
 
执行结果:
 
define函数:
 
0.000098943710327148
0.00010895729064941
0.00010585784912109
0.00010395050048828
 
apc常量定义:
 
0.00010991096496582
0.000039100646972656
0.000042915344238281
0.000041961669921875
 
从结果可以看出,apc常量定义在第一次执行时,花的时间和define差不多;但是在第一次执行后,后面的执行时间非常地少,只有define的三分之一。而define执行的时间,每次都很平均,并没有太大的起伏。
从代码上分析,apc常量定义是先通过apc_load_constants()函数获取常量,当常量不存在时再执行apc_define_constants()来定义常量。这样的好处是一次性将常量导入到PHP执行空间内,不需要每个都define一次,所以效率更高。
注:本次测试,PHP环境开启了apc缓存,所以define函数的测试也是在内存级运行。