哪个更快?常量,变量或变量数组

Dav*_*vid 23 php variables optimization performance constants

我当前的Web应用程序使用大约30个左右的Contants(DEFINE()).我正在读变量更快的东西.如果存在一个避免变量覆盖的命名约定,那么我看到的唯一其他缺点就是这些变量必须在每个函数中定义为全局变量.

哪个更快?我在整个应用程序中使用了这些常量,并且可能会永远在列表中添加更多常量,并且它们可以在函数和类中使用.

Nik*_*kiC 23

使用定义的常量define()在PHP中相当慢.人们实际上编写了扩展(如hidef)来提高性能.

但除非你有大量的常数,否则这应该没什么区别.

从PHP 5.3开始,您还可以使用编译时常量const NAME = VALUE;.那些更快.

  • 你的负荷定义是什么?我有大约30个,每页引用100次 (4认同)

str*_*str 11

差异非常小(微优化).您最好将一些常量封装在类中,以便可以通过Classname::CONSTANT不污染应用程序的全局命名空间来访问它们.


Ara*_*ram 8

快速测试表明,定义常量(define('FOO', 'bar');)比定义变量($foo = 'bar';)慢大约16到18倍,但使用定义的(常量)值大约快4到6倍.


Anj*_*lva 7

我对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

谢谢。