PHP类属性3种不同访问方式的性能测试

PHP给了我们3种访问类属性的方法,我们来测试以下他们的性能差异。

1.直接访问

class dog { 
    public $name = "";
} 
$rover = new dog(); 
for ($x=0; $x<10; $x++) { 
    $t = microtime(true); 
    for ($i=0; $i<1000000; $i++) { 
        $rover->name = "rover"; 
        $n = $rover->name;
    } 
    echo microtime(true) - $t;echo "\n";
}

2.使用类函数访问

class dog {
    public $name = "";

    public function setName($name) {
        $this->name = $name; 
    }

    public function getName() {
        return $this->name; 
    } 
}

$rover = new dog();
for ($x=0; $x<10; $x++) { 
    $t = microtime(true);
    for ($i=0; $i<1000000; $i++) { 
        $rover->setName("rover");
        $n = $rover->getName();
    }
    echo microtime(true) - $t;echo "\n";
}

3.使用PHP提供的魔术方法__set和__get访问

class dog { 
    private $data = array();
    function __set($name, $value) {
        $this->data[$name] = $value;
    }
    function __get($name) {
        if(array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
        return null;
    }
} 
$rover = new dog(); 
for ($x=0; $x<10; $x++) { 
    $t = microtime(true); 
    for ($i=0; $i<1000000; $i++) { 
        $rover->name = "rover"; 
        $n = $rover->name;
    } 
    echo microtime(true) - $t;echo "\n";
}

执行结果分别为:

1.直接访问

0.59869480133057
0.59985685348511
0.61411023139954
0.61089015007019
0.59671401977539
0.60318994522095
0.60059809684753
0.59980893135071
0.59794902801514
0.59721207618713

2.使用类函数访问

4.107736825943
4.0344598293304
4.009449005127
4.0501089096069
4.070415019989
4.0576939582825
4.0664989948273
4.0609030723572
4.0520219802856
4.0485868453979

3.使用PHP提供的魔术方法__set和__get访问

7.6956799030304
7.810909986496
7.7758450508118
7.7235188484192
7.7205560207367
7.7772619724274
7.9401290416718
7.8542349338531
7.8687150478363
7.9177348613739

差距还是挺大的。

为了让大家方便自己测试,下面把3种直接可以在命令行执行的代码整理出来:

php -d implicit_flush=off -r  'class dog { public $name = "";} $rover = new dog(); for ($x=0; $x<10; $x++) { $t = microtime(true); for ($i=0; $i<1000000; $i++) { $rover->name = "rover"; $n = $rover->name;} echo microtime(true) - $t;echo "\n";}'

php -d implicit_flush=off -r  'class dog {public $name = "";public function setName($name) {$this->name = $name; }public function getName() {return $this->name; } }$rover = new dog();for ($x=0; $x<10; $x++) { $t = microtime(true);for ($i=0; $i<1000000; $i++) { $rover->setName("rover");$n = $rover->getName();}echo microtime(true) - $t;echo "\n";}'

php -d implicit_flush=off -r 'class dog { private $data = array();function __set($name, $value) {$this->data[$name] = $value;}function __get($name) {if(array_key_exists($name, $this->data)) {return $this->data[$name];}return null;}} $rover = new dog(); for ($x=0; $x<10; $x++) { $t = microtime(true); for ($i=0; $i<1000000; $i++) { $rover->name = "rover"; $n = $rover->name;} echo microtime(true) - $t;echo "\n";}'

你们结果如何?

(End)