php5.3 使用namespace后性能比较及类、函数、静态方法的性能比较

来源:互联网 发布:泳帽pu 硅胶 知乎 编辑:程序博客网 时间:2024/05/16 19:40

这里不是为了做复杂测试,主要是工作需要,分析一些新设计有多少使用必要,及其影响。连带的就把类方法,类静态方法,函数等的使用性能差别及内存差异进行比较.

测试环境

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、直接调用比魔术要快很多,而且内存使用少

原创粉丝点击