Recently, when I was working on the preliminary code architecture of the cloud platform, I encountered a constant definition speed comparison problem, so I would like to make a comparison.
The APC extension of PHP is described in the following section in the PHP manual:
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.
This means that PHP's define function is relatively slow. In the PHP environment where apc is enabled, the constant definition method using apc is much faster than define.
The apc constant definition uses the apc_define_constants () and apc_load_constants () functions.
Here we have prepared two programs to test their running time respectively:
Code of the define function:
<? Php
$ Stime = microtime (true );
Define ('tmp _ path', '/TMP ');
//... Other definitions, 20 in total
Echo API_MAIL;
Echo '<br/> ';
$ Etime = microtime (true );
Echo $ etime-$ stime;
?>
The constant definition code of apc:
<? Php
$ Stime = microtime (true );
If (! Apc_load_constants ('api ')){
Apc_define_constants ('api ', array (
'Tmp _ path' => '/TMP ',
//... Other definitions, 20 in total
));
}
Echo API_MAIL;
Echo '<br/> ';
$ Etime = microtime (true );
Echo $ etime-$ stime;
?>
Execution result:
Define function:
0.000098943710327148
0.00010895729064941
0.00010585784912109
0.00010395050048828
...
Apc constant definition:
0.00010991096496582
0.000039100646972656
0.000042915344238281
0.000041961669921875
...
From the results, we can see that the apc constant definition takes almost the same time as define during the first execution, but after the first execution, the execution time is very small, only 1/3 of define. The execution time of define is very average every time, and there is not much ups and downs.
From code analysis, the definition of apc constant is to get a constant through the apc_load_constants () function, and then execute apc_define_constants () to define a constant when the constant does not exist. The advantage is that constants are imported to the PHP Execution space at a time, so they do not need to be define once, so the efficiency is higher.
Note: In this test, the apc cache is enabled in the PHP environment, so the test of the define function is also executed in memory.
This article is from the "Zhenzhong technical notebook" blog