Skip to content

Instantly share code, notes, and snippets.

@rybakit
Last active December 29, 2016 10:43
Show Gist options
  • Save rybakit/1f58d32cd29690dea93ce876485f9591 to your computer and use it in GitHub Desktop.
Save rybakit/1f58d32cd29690dea93ce876485f9591 to your computer and use it in GitHub Desktop.
Bench php7 encapsed strings optimization
<?php
// https://blog.blackfire.io/php-7-performance-improvements-encapsed-strings-optimization.html
class Foobar
{
public function getVal1()
{
return rand(0, 1000);
}
public function getVal2()
{
return rand(1000, 2000);
}
}
function str_concat($n, $obj) {
$data = '';
for ($i = 0; $i < $n; ++$i) {
$data .= $obj->getVal1();
$data .= $obj->getVal2();
}
}
function str_interpol($n, $obj) {
$data = '';
for ($i = 0; $i < $n; ++$i) {
$data = "$data{$obj->getVal1()}{$obj->getVal2()}";
}
}
function str_interpol2($n, $obj) {
$data = '';
for ($i = 0; $i < $n; ++$i) {
$data .= "{$obj->getVal1()}{$obj->getVal2()}";
}
}
function empty_loop($n) {
for ($i = 0; $i < $n; ++$i) {
}
}
function getmicrotime()
{
$t = gettimeofday();
return ($t['sec'] + $t['usec'] / 1000000);
}
function start_test()
{
ob_start();
return getmicrotime();
}
function end_test($start, $name, $overhead = null)
{
global $total;
global $last_time;
$end = getmicrotime();
ob_end_clean();
$last_time = $end-$start;
$total += $last_time;
$num = number_format($last_time,3);
$pad = str_repeat(" ", 30 - strlen($name) - strlen($num));
if (is_null($overhead)) {
echo $name.$pad.$num."\n";
} else {
$num2 = number_format($last_time - $overhead, 3);
echo $name.$pad.$num." ".$num2."\n";
}
ob_start();
return getmicrotime();
}
$total = $last_time = 0;
$obj = new Foobar();
$n = 200000;
$t = start_test();
empty_loop($n);
$t = end_test($t, "empty_loop($n)");
$overhead = $last_time;
str_concat($n, $obj);
$t = end_test($t, "str_concat($n)", $overhead);
str_interpol($n, $obj);
$t = end_test($t, "str_interpol($n)", $overhead);
str_interpol2($n, $obj);
$t = end_test($t, "str_interpol2($n)", $overhead);
$ php bench_concat_vs_interpol.php
empty_loop(200000) 0.002
str_concat(200000) 0.074 0.072
str_interpol(200000) 11.937 11.935
str_interpol2(200000) 0.073 0.071
$ php bench_concat_vs_interpol.php
empty_loop(200000) 0.002
str_concat(200000) 0.074 0.072
str_interpol(200000) 10.965 10.963
str_interpol2(200000) 0.077 0.075
$ php bench_concat_vs_interpol.php
empty_loop(200000) 0.002
str_concat(200000) 0.077 0.075
str_interpol(200000) 9.944 9.942
str_interpol2(200000) 0.075 0.073
$ php -v
PHP 7.1.0 (cli) (built: Dec 20 2016 17:28:16) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.1.0-dev, Copyright (c) 1998-2016 Zend Technologies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment