這裡不是為了做複雜測試,主要是工作需要,分析一些新設計有多少使用必要,及其影響。連帶的就把類方法,類靜態方法,函數等的使用效能差別及記憶體差異進行比較.
測試環境
WIN7 + Apache2.2 + PHP5.3.17
1、使用namespace後的效能差別,代碼執行10000次字串拼接:
namespace performance;function getMsecTime(){ $arr = explode( ' ', microtime() ); return $arr[0] + $arr[1]; }//執行10000次字串串連$start = getMsecTime();$i = 0;$str = "";while(true) { $i++; $str .= "adefd"; if ($i >= 10000) break;}echo "Running Time:" , getMsecTime() - $start , "\n";echo "Memory usage:" , memory_get_usage() , "\n";
使用namespace
Running Time:0.01677393913269
Memory usage:375504
不使用namespace
Running Time:0.0022430419921875
Memory usage:374264
2、比較類方法,類靜態方法,函數的效能差異,執行十萬次加運算
class test{ public function get() { $j = 1; for($i=0;$i<100000;$i++) $j++; echo __CLASS__, "\n"; } public static function staticget() { $j = 1; for($i=0;$i<100000;$i++) $j++; echo "static method:", __CLASS__, "\n"; }}function get(){ $j = 1; for($i=0;$i<100000;$i++) $j++; echo __FUNCTION__,"\n";}$start = getMsecTime();$a = new test;$a->get();echo "Running Time:" , getMsecTime() - $start , "\n";echo "Memory usage:" , memory_get_usage() , "\n";
類方法
Running Time:0.016539096832275
Memory usage:329808
類靜態方法
Running Time:0.018104076385498
Memory usage:329224
函數
Running Time:0.013308048248291
Memory usage:329104
在最開始使用類靜態方法做簡單輸出(沒有大量計算操作)的時候,靜態方法要快上1/5,但是做計算後速度明顯減慢,不明就裡看來只能通過看底層實現理解了
魔術get、set方法和一般類方法的效能差距
class test{ private $arr = array(); public function get() { $j = 1; for($i=0;$i<100000;$i++) $j++; echo __CLASS__, "\n"; } public static function staticget() { $j = 1; for($i=0;$i<100000;$i++) $j++; echo "static method:", __CLASS__, "\n"; } public function __get($key) { if ($this->arr[$key]) return $this->arr[$key]; } public function __set($key, $val) { $this->arr[$key] = $val; } public function getter($key) { if ($this->arr[$key]) return $this->arr[$key]; } public function setter($key, $val) { $this->arr[$key] = $val; }}$start = getMsecTime();$a = new test;for($i=0; $i<100000;$i++) $a->$i = $i;for($i=0; $i<100000;$i++) $a->$i;echo "Running Time:" , getMsecTime() - $start , "\n";echo "Memory usage:" , memory_get_usage() , "\n";
魔術方法
Running Time:0.33731293678284
Memory usage:16501560
一般類方法
Running Time:0.2406919002533
Memory usage:8860024
測試總結:
1、namespace 設計上需要用,該用著用,其他別用
2、全域函數最快,在進行大量計算的情況下類執行個體調用更快,沒有大量計算的操作類靜態方法更快
3、直接調用比魔術要快很多,而且記憶體使用量少