静态与动态类功能(方法) - 哪个更快?

时间:2012-02-10 04:47:20

标签: php performance optimization

有没有人对这三种foo函数之间的性能差异做了适当的基准测试?

function foo_global() {
}

class SomeClass {
  public function foo_dynamic() {
  }

  public static function foo_static() {
  }
}

据我所知,全球性是最快和最动态的,但我会更加欣赏一些学到的结果。

由于

1 个答案:

答案 0 :(得分:4)

在我的测试中几乎没有区别:

Function call benchmark

因此静态调用比动态稍慢,而动态比全局函数稍慢。

<?php
function pre_defined($v1, $v2) {
    return $v1 + $v2;
}
$anonymous = function($v1, $v2) {
    return $v1 + $v2;
};
$create_function = create_function('$v1, $v2', 'return $v1 + $v2;');

class StaticFunction {
    public static function test($v1, $v2) {
        return $v1 + $v2;
    }
}

class DynamicFunction {
    public function test($v1, $v2) {
        return $v1 + $v2;
    }
}
$dynamic = new DynamicFunction();

$v1 = 1;
$v2 = 2;
$iterations = 1000;
Performance\BenchmarkManager::add_group('Function call', new Performance\BenchmarkGroup(array(
    'benchmarks' => array(
        'empty loop' => function() use($iterations, $v1, $v2) {
            for ($i = 0; $i < $iterations; $i++) {
            }
        },
        'native reference point' => function() use($iterations, $v1, $v2) {
            for ($i = 0; $i < $iterations; $i++) {
                $result = $v1 + $v2;
            }
        },
        'pre defined' => function() use($iterations, $v1, $v2) {
            for ($i = 0; $i < $iterations; $i++) {
                $result = pre_defined($v1, $v2);
            }
        },
        'anonymous' => function() use($iterations, $v1, $v2, $anonymous) {
            for ($i = 0; $i < $iterations; $i++) {
                $anonymous($v1, $v2);
            }
        },
        'create_function' => function() use($iterations, $v1, $v2, $create_function) {
            for ($i = 0; $i < $iterations; $i++) {
                $create_function($v1, $v2);
            }
        },
        'eval' => function() use($iterations, $v1, $v2) {
            for ($i = 0; $i < $iterations; $i++) {
                eval('$result = $v1 + $v2;');
            }
        },
        'static' => function() use($iterations, $v1, $v2) {
            for ($i = 0; $i < $iterations; $i++) {
                StaticFunction::test($v1, $v2);
            }
        },
        'dynamic' => function() use($iterations, $v1, $v2, $dynamic) {
            for ($i = 0; $i < $iterations; $i++) {
                $dynamic->test($v1, $v2);
            }
        },
    ),
)));