APC常量定义与PHP的define比较

最近在做云平台的初步代码架构时,遇到一个常量定义速度比较的问题,故做一下比较。
PHP的APC扩展,在PHP手册里面有下面一段描述:
http://cn.php.net/manual/zh/function.apc-define-constants.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函数的代码:
<?php  
$stime=microtime(true); 
  
define('TMP_PATH', '/tmp'); 
// ...其他定义,共20个 
  
echo API_MAIL; 
echo ''; 
  
$etime=microtime(true); 
echo $etime-$stime; 
?> 


apc的常量定义代码:
<?php 
$stime=microtime(true); 
if(!apc_load_constants('API')){ apc_define_constants('API', array( 'TMP_PATH' =--> '/tmp', 
// ...其他定义,共20个 
)); 
} 
  
echo API_MAIL; 
echo ''; 
 
$etime=microtime(true); 
echo $etime-$stime; 
?> 




执行结果:

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函数的测试也是在内存级运行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值