PHP类中Static方法效率测试代码
因为有好几个项目等着做,又不是很急,再加上目前成型的那些框架多多少少用着总是有点不太如意,所以决定先自己写一个框架,然后再做项目。既然写框架,自然要经常做一些执行效率上的测试,今天做了一个static效率的测试。
类的定义如下:
<div class="codetitle"><a style="CURSOR: pointer" data="27228" class="copybut" id="copybut27228" onclick="doCopy('code27228')"> 代码如下:
<div class="codebody" id="code27228">
class test
{
public static function a(){}
public function b(){}
}
$obj = new test;
比较以下几种情况
test::a();
$obj->a();
$obj->b();
测试代码:
<div class="codetitle">
<a style="CURSOR: pointer" data="18942" class="copybut" id="copybut18942" onclick="doCopy('code18942')"> 代码如下: <div class="codebody" id="code18942">
$obj = new test;
$test_times = 100;
$times = 10000;
$effi1 = array();
$effi2 = array(); while ($test_times-- > 0)
{
$time1 = microtime(true);
for($i=0; $i<$times; $i++)
{
test::a();
}
$time2 = microtime(true);
for($i=0; $i<$times; $i++)
{
$obj->a();
}
$time3 = microtime(true);
for($i=0; $i<$times; $i++)
{
$obj->b();
}
$time4 = microtime(true);
$effi1[] = ($time3 - $time2) / ($time2 - $time1);
$effi2[] = ($time4 - $time3) / ($time3 - $time2);
}
echo avg($effi1),"\n",avg($effi2);
最后的avg是自定义的计算平均数的一个函数:
<div class="codetitle">
<a style="CURSOR: pointer" data="96916" class="copybut" id="copybut96916" onclick="doCopy('code96916')"> 代码如下: <div class="codebody" id="code96916">
function avg($arr)
{
$result = 0;
foreach ($arr as $val)
{
$result += $val;
}
$result /= count($arr);
return $result;
}
程序输出结果:
<div class="codetitle">
<a style="CURSOR: pointer" data="36437" class="copybut" id="copybut36437" onclick="doCopy('code36437')"> 代码如下: <div class="codebody" id="code36437">
PHP 5.2.14
view sourceprint?1 0.76490628848091
2 1.0699484376399
view sourceprint?1 PHP 5.3
view sourceprint?1 0.56919482299058
1.1016495598611