Dav*_*vid 23 php variables optimization performance constants
我当前的Web应用程序使用大约30个左右的Contants(DEFINE()).我正在读变量更快的东西.如果存在一个避免变量覆盖的命名约定,那么我看到的唯一其他缺点就是这些变量必须在每个函数中定义为全局变量.
哪个更快?我在整个应用程序中使用了这些常量,并且可能会永远在列表中添加更多常量,并且它们可以在函数和类中使用.
我对constantsvs进行了基准测试,发现使用overvariables时性能显着提高。我知道这是非常明显的,但绝对值得考虑尽可能使用局部变量而不是常量。variablesconstants
如果constants在内部多次使用loops,则绝对值得将常量声明为类/局部变量并使用它。
基准测试用例包括创建两个函数。每个都有一个执行10000000多次的循环。一种访问常量文件中声明的常量,另一种访问局部变量。
测试常量.php
class TestConstants
{
const TEST_CONSTANT = 'This is a constant value';
}
Run Code Online (Sandbox Code Playgroud)
测试.php
use TestConstants;
class Test {
protected $TEST_CONSTANT;
protected $limit = 10000000;
function __construct() {
$this->TEST_CONSTANT = 'This is a constant value';
}
function testA() {
$limit = $this->limit;
$time_start = microtime(true);
for ($i = 0; $i < $limit; ++$i) {
TestConstants::TEST_CONSTANT;
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
echo ''. $execution_time .' seconds <br/>';
}
function testB() {
$limit = $this->limit;
$time_start = microtime(true);
for ($i = 0; $i < $limit; ++$i) {
$this->TEST_CONSTANT;
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
echo ''. $execution_time .' seconds <br/>';
}
}
$test = new Test();
$test->testA();
$test->testB();
Run Code Online (Sandbox Code Playgroud)
结果如下
testA() 在 0.55921387672424 秒内执行
和
testB() 在 0.33076691627502 秒内执行
PHP版本
5.6.30
我想分享这一点,因为通过在适用的地方声明它们来避免直接调用constants(特别是内部循环),可能会受益于其他人variables。
谢谢。
| 归档时间: |
|
| 查看次数: |
11545 次 |
| 最近记录: |