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

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

测试环境

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值