函数返回值是否会影响PHP的性能?

时间:2016-06-07 09:46:57

标签: php performance benchmarking

让我们来看看这个类和方法:

class Test {
    protected $storage;

    public function rng() {
        $random = random_bytes(100);

        $this->storage = $random;
    }
}

使用PHP7的random_bytes()函数计算一些随机字节,并且不返回结果;它只存储在一个属性中。

让我们看一下上述方法略有不同的版本:

class Test {
    protected $storage;

    public function rng() {
        $random = random_bytes(100);

        $this->storage = $random;

        return $random;
    }
}

这次,返回结果。我想知道在返回值时是否有任何性能损失。

1 个答案:

答案 0 :(得分:3)

测试脚本#1:不返回值

<?php

class Test {
    protected $storage;

    public function rng() {
        $random = random_bytes(100);

        $this->storage = $random;
    }
}

$instance = new Test;

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    $instance->rng();
}

$end = microtime(true);

$diff = $end - $start;

printf('Not returning: %.25f', $diff);

print PHP_EOL;

测试脚本#2:返回值

<?php

class Test {
    protected $storage;

    public function rng() {
        $random = random_bytes(100);

        $this->storage = $random;

        return $random;
    }
}

$instance = new Test;

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    $instance->rng();
}

$end = microtime(true);

$diff = $end - $start;

printf('Returning: %.25f', $diff);

print PHP_EOL;

结果:

$ php -f functions-returning-values-benchmark.php
Not returning: 0.0937850475311279296875000

$ php -f functions-returning-values-benchmark.php
Not returning: 0.0939409732818603515625000

$ php -f functions-returning-values-benchmark.php
Not returning: 0.0953028202056884765625000

$ php -f functions-returning-values-benchmark.php
Returning: 0.0947949886322021484375000

$ php -f functions-returning-values-benchmark.php
Returning: 0.0930099487304687500000000

$ php -f functions-returning-values-benchmark.php
Returning: 0.0935621261596679687500000

结论

没有性能受损。

在运行PHP 7.0.7的AWS Debian Jessie t2.micro实例(1vCore,1 GiB RAM)上测试。