Home > Backend Development > PHP Tutorial > PHP程序中Static方法效率的测试

PHP程序中Static方法效率的测试

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 14:24:24
Original
1271 people have browsed it

因为有好几个项目等着做,又不是很急,再加上目前成型的那些框架多多少少用着总是有点不太如意,所以决定先自己写一个框架,然后再做项目。既然写框架,自然要经常做一些执行效率上的测试,今天做了一个static效率的测试。

类的定义如下:

class test
{
    public static function a(){}
    public function b(){}
}
Copy after login

比较以下几种情况

  1. test::a();
  2. $obj->a();
  3. $obj->b();

测试代码:

$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);
Copy after login

最后的avg是自定义的计算平均数的一个函数:

function avg($arr)
{
    $result = 0;
    foreach ($arr as $val)
    {
        $result += $val;
    }

    $result /= count($arr);
    return $result;
}
Copy after login

程序输出结果:

PHP 5.2.14
Copy after login

0.76490628848091
1.0699484376399
Copy after login

PHP 5.3
Copy after login

0.56919482299058<BR>1.1016495598611
Copy after login

 

重复执行N(N>10)次,都与这个结果相差不大,说明:

  1. 直接通过类名访问静态方法的效率是通过实例访问静态方法的76%,甚至用PHP5.3时只有56%
  2. 通过实例访问静态方法的效率是访问非静态成员方法效率的106,在5.3版本变成110%
  3. 假设PHP从5.2升级到5.3时通过类名访问静态方法的效率没有降低,那么通过实例访问函数的效率至少提高了35%。我没看过PHP源码,有研究过PHP源码的朋友希望能告诉我这个假设是否成立 (我想应该是成立的)

说明:以上测试基于windows 7和php.exe,5.2.14使用了apache2.2测试结果没有区别,考虑到php.exe和通过web访问所执行的PHP核心是一样的,所以5.3懒得改服务器配置了,结果应该一样。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template