4

今天早些时候,我正在开发一个 PHP 5.3+ 应用程序,这意味着我可以自由地使用 PHP 闭包。太好了,我想!然后我遇到了一段代码,其中使用函数式 PHP 代码会使事情变得更容易,但是,虽然我有一个合乎逻辑的答案,但它让我想知道直接调用闭包array_map()和传递闭包之间的性能影响是什么向下作为变量。即以下两个:

$test_array = array('test', 'test', 'test', 'test', 'test' );
array_map( function ( $item ) { return $item; }, $test_array );

$test_array = array('test', 'test', 'test', 'test', 'test' );
$fn = function ( $item ) { return $item; };
array_map( $fn, $test_array );

和我想的一样,后者确实更快,但差别并没有那么大。事实上,重复这些相同的测试 10000 次并取平均值的差异是 0.05 秒。甚至可能是侥幸。

这让我更加好奇了。什么create_function()和关闭?同样,经验告诉我,当它创建一个函数、评估它,然后也存储它create_function()时,应该更慢一些。array_map()再一次,正如我所想的那样,create_function()确实慢了。这一切都与array_map().

然后,我不确定我为什么这样做,但我做到了,我检查了create_function()和闭包之间的区别,同时保存它并只调用它一次。没有处理,什么都没有,只是简单地传递一个字符串,然后返回该字符串。

测试变成了:

$fn = function($item) { return $item; };
$fn('test');

$fn = create_function( '$item', 'return $item;' );
$fn('test');

我分别运行了这两个测试 10000 次,并查看了结果并得到了平均值。我对结果感到非常惊讶。

事实证明,这次关闭速度慢了大约 4 倍。这不可能是我想的。我的意思是,运行闭包array_map()要快得多,而通过变量运行相同的函数array_map()要快得多,这实际上与这个测试相同。

结果是

array
  0 => 
    array
      'test' => string 'Closure test' (length=12)
      'iterations' => int 10000
      'time' => float 5.1327705383301E-6
  1 => 
    array
      'test' => string 'Anonymous test' (length=14)
      'iterations' => int 10000
      'time' => float 1.6745710372925E-5

很好奇为什么会这样,我检查了 CPU 使用率和其他系统资源,并确保没有运行任何不必要的东西,现在一切都很好,所以我再次运行测试,但我得到了类似的结果。

所以我只尝试了一次相同的测试,并运行了多次(当然每次都计时)。事实证明,关闭确实慢了 4 倍,除了偶尔会比 快两到三倍create_function(),我猜这只是侥幸,但这似乎足以将时间缩短一半我做了1000次测试。

下面是我用来进行这些测试的代码。谁能告诉我这里到底发生了什么?是我的代码还是只是 PHP 在起作用?

<?php

/**
 * Simple class to benchmark code
 */
class Benchmark
{
    /**
     * This will contain the results of the benchmarks.
     * There is no distinction between averages and just one runs
     */
    private $_results = array();

    /**
     * Disable PHP's time limit and PHP's memory limit!
     * These benchmarks may take some resources
     */
    public function __construct() {
        set_time_limit( 0 );
        ini_set('memory_limit', '1024M');
    }

    /**
     * The function that times a piece of code
     * @param string $name Name of the test. Must not have been used before
     * @param callable|closure $callback A callback for the code to run.
     * @param boolean|integer $multiple optional How many times should the code be run,
     * if false, only once, else run it $multiple times, and store the average as the benchmark
     * @return Benchmark $this
     */
    public function time( $name, $callback, $multiple = false )
    {
        if($multiple === false) {
            // run and time the test
            $start = microtime( true );
            $callback();
            $end = microtime( true );

            // add the results to the results array
            $this->_results[] = array(
                'test' => $name,
                'iterations' => 1,
                'time' => $end - $start
            );
        } else {
            // set a default if $multiple is set to true
            if($multiple === true) {
                $multiple = 10000;
            }

            // run the test $multiple times and time it every time
            $total_time = 0;
            for($i=1;$i<=$multiple;$i++) {
                $start = microtime( true );
                $callback();
                $end = microtime( true );
                $total_time += $end - $start;
            }
            // calculate the average and add it to the results
            $this->_results[] = array(
                'test' => $name,
                'iterations' => $multiple,
                'time' => $total_time/$multiple
            );
        }
        return $this; //chainability
    }

    /**
     * Returns all the results
     * @return array $results
     */
    public function get_results()
    {
        return $this->_results;
    }
}

$benchmark = new Benchmark();

$benchmark->time( 'Closure test', function () {
    $fn = function($item) { return $item; };
    $fn('test');
}, true);

$benchmark->time( 'Anonymous test', function () {
    $fn = create_function( '$item', 'return $item;' );
    $fn('test');
}, true);

$benchmark->time( 'Closure direct', function () {
    $test_array = array('test', 'test', 'test', 'test', 'test' );
    $test_array = array_map( function ( $item ) { return $item; }, $test_array );
}, true);

$benchmark->time( 'Closure stored', function () {
    $test_array = array('test', 'test', 'test', 'test', 'test' );
    $fn = function ( $item ) { return $item; };
    $test_array = array_map( $fn, $test_array );
}, true);

$benchmark->time( 'Anonymous direct', function () {
    $test_array = array('test', 'test', 'test', 'test', 'test' );
    $test_array = array_map( create_function( '$item', 'return $item;' ), $test_array );
}, true);

$benchmark->time( 'Anonymous stored', function () {
    $test_array = array('test', 'test', 'test', 'test', 'test' );
    $fn = create_function( '$item', 'return $item;' );
    $test_array = array_map( $fn, $test_array );
}, true);

var_dump($benchmark->get_results());

这段代码的结果:

array
  0 => 
    array
      'test' => string 'Closure test' (length=12)
      'iterations' => int 10000
      'time' => float 5.4110765457153E-6
  1 => 
    array
      'test' => string 'Anonymous test' (length=14)
      'iterations' => int 10000
      'time' => float 1.6784238815308E-5
  2 => 
    array
      'test' => string 'Closure direct' (length=14)
      'iterations' => int 10000
      'time' => float 1.5178990364075E-5
  3 => 
    array
      'test' => string 'Closure stored' (length=14)
      'iterations' => int 10000
      'time' => float 1.5463256835938E-5
  4 => 
    array
      'test' => string 'Anonymous direct' (length=16)
      'iterations' => int 10000
      'time' => float 2.7537250518799E-5
  5 => 
    array
      'test' => string 'Anonymous stored' (length=16)
      'iterations' => int 10000
      'time' => float 2.8293371200562E-5
4

2 回答 2

19

5.1327705383301E-6 is not 4 times slower than 1.6745710372925E-5; it is about 3 times faster. You are reading the numbers wrong. It seems that in all of your results, the closure is consistently faster than the create_function.

于 2012-07-01T21:14:15.097 回答
2

请参阅此基准:

<?php
$iter = 100000;


$start = microtime(true);
for ($i = 0; $i < $iter; $i++) {}
$end = microtime(true) - $start;
echo "Loop overhead: ".PHP_EOL;
echo "$end seconds".PHP_EOL;

$start = microtime(true);
for ($i = 0; $i < $iter; $i++) {
    $fn = function($item) { return $item; };
    $fn('test');
}
$end = microtime(true) - $start;
echo "Lambda function: ".PHP_EOL;
echo "$end seconds".PHP_EOL;


$start = microtime(true);
for ($i = 0; $i < $iter; $i++) {
    $fn = create_function( '$item', 'return $item;' );
    $fn('test');
}
$end = microtime(true) - $start;
echo "Eval create function: ".PHP_EOL;
echo "$end seconds".PHP_EOL;

结果:

Loop overhead: 
0.011878967285156 seconds
Lambda function: 
0.067019939422607 seconds
Eval create function: 
1.5625419616699 seconds

现在,有趣的是,如果将函数声明放在for 循环之外:

Loop overhead: 
0.0057950019836426 seconds
Lambda function: 
0.030204057693481 seconds
Eval create function: 
0.040947198867798 seconds

为了回答您最初的问题,将 lambda 函数分配给变量和简单地使用它没有区别。除非您多次使用它,否则在这种情况下使用变量会更好地提高代码清晰度

于 2012-07-01T01:03:02.260 回答