PHP Performance Tip

To improve the performance of your PHP application, you should work with object properties directly, rather than writing naive settings and getters. If you need getter/setters, you can use the __get and __set magic methods.

I have performed a quick test with the following script (base code is from google performance tips) to show the performance savings.

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”;}’
0.27138209342957
0.27215003967285
0.27119302749634
0.27127695083618
0.27089595794678
0.27323412895203
0.27595901489258
0.27139592170715
0.27534413337708
0.27470207214355

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”;}’
0.88418102264404
0.90805292129517
0.88095903396606
0.9102931022644
0.88606786727905
0.91241002082825
0.88503313064575
0.90973210334778
0.87963604927063
0.91335105895996

php -d implicit_flush=off -r ‘class dog {public $name = “”;public function __set($key, $value) {$this->$key = $value;}public function __get($key) {return $this->$key;}}$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”;}’
0.27974605560303
0.28078198432922
0.27995705604553
0.280522108078
0.27998900413513
0.28067207336426
0.27970504760742
0.28028988838196
0.27951693534851
0.28037190437317

Tags: ,

Leave a Reply

You must be logged in to post a comment.