Let's take a look at this class and method:
class Test {
protected $storage;
public function rng() {
$random = random_bytes(100);
$this->storage = $random;
}
}
Some random bytes are being calculated using PHP7's random_bytes() function, and the result isn't returned; it's only being stored in a property.
Let's take a look at a slightly different version of the above method:
class Test {
protected $storage;
public function rng() {
$random = random_bytes(100);
$this->storage = $random;
return $random;
}
}
This time, the result is returned. I am wondering if there's any performance hit when a value is being returned.
Test script #1: not returning value
<?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;
Test script #2: returning value
<?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;
Results:
$ 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
There is no performance hit.
Tested on AWS Debian Jessie t2.micro instance (1vCore, 1 GiB RAM) running PHP 7.0.7.