当前位置: 移动技术网 > IT编程>开发语言>PHP > APC常量定义与PHP的define比较

APC常量定义与PHP的define比较

2019年06月19日  | 移动技术网IT编程  | 我要评论

最近在做云平台的初步代码架构时,遇到一个常量定义速度比较的问题,故做一下比较。
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函数的代码:
<?php
$stime=microtime(true);
 
define('tmp_path', '/tmp');
// ...其他定义,共20个
 
echo api_mail;
echo '<br />';
 
$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 '<br />';
 
$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函数的测试也是在内存级运行。
 
 
本文出自 “振中的技术记事本” 博客

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网