PHP 闭包给出了奇怪的性能行为

标签 php performance closures anonymous-function

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

$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

最佳答案

5.1327705383301E-6 不比 1.6745710372925E-5 慢 4 倍;它快了大约 3 倍。你读错了数字。似乎在您的所有结果中,闭包始终比 create_function 快。

关于PHP 闭包给出了奇怪的性能行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278748/

相关文章:

php - php-cli 和 php-fpm 模式在 APC/APCu 方面的区别

php - Typeahead.js 出现问题

performance - 如何优化 docker 容器的性能?

java - java中哪个更快

javascript - 使用 valueOf 数学运算进行类型强制

swift - 使用 "self."前缀和在闭包的捕获列表中写入 "self"有什么区别?

swift - 如何在快速闭包中实现单向引用

php - 如何在 PHP 中发送 HTTP/2 POST 请求

php - 从数据库中选择值的下拉列表 php

c++ - 快速复制 `std::vector<std::uint8_t>`