Skip to content

Instantly share code, notes, and snippets.

@xavierbriand
Last active April 24, 2018 19:01
Show Gist options
  • Save xavierbriand/83693e9732c82ef5382a65ab41b63c2b to your computer and use it in GitHub Desktop.
Save xavierbriand/83693e9732c82ef5382a65ab41b63c2b to your computer and use it in GitHub Desktop.
PHP Loops benchmark
<?php
for ($i = 0; $i < $boundary; $i++) {
$acc++;
}
<?php
for (; $boundary--;) {
$acc++;
}
<?php
for (; $acc <= $boundary; $acc++) {
}
<?php
start:
$acc++;
if (--$boundary) {
goto start;
}
<?php
$iteration = $boundary = pow(10, 8);
$acc = 0;
$startTime = microtime(true);
echo 'Starting '.$argv[1]."...\n";
$file = './'.$argv[1].'.php';
echo file_get_contents($file);
include $file;
echo microtime(true) - $startTime . "s\n";
echo number_format($iteration) . " iterations \n";
echo number_format($acc) . " accumulated \n";
echo memory_get_peak_usage() / 1000 . "MB\n\n\n";
<?php
class A {
private $boundary;
private $acc;
public function __construct($boundary, $acc) {
$this->boundary = $boundary;
$this->acc = $acc;
}
public function __destruct() {
global $loop, $acc;
if ($this->boundary) {
$acc++;
$loop = new A(--$this->boundary, $acc);
} else {
echo number_format($acc) . " accumulated \n";
}
}
}
$loop = new A($boundary, $acc);
<?php
$callback = function($boundary, $acc) use (&$callback) {
return $boundary ? $callback($boundary--, $acc++) : $acc;
};
$acc = $callback($boundary, $acc);
<?php
function callback($boundary, $acc) {
if ($boundary) {
return function () use ($boundary, $acc) {
return callback(--$boundary, ++$acc);
};
}
return $acc;
};
function trampoline($fn, $args) {
while (is_callable($fn)) {
$fn = call_user_func_array($fn, $args);
}
return $fn;
}
$acc = trampoline('callback', [$boundary, $acc]);
php -d memory_limit=500M -d max_execution_time=60 main.php for1
php -d memory_limit=500M -d max_execution_time=60 main.php for2
php -d memory_limit=500M -d max_execution_time=60 main.php while
php -d memory_limit=500M -d max_execution_time=60 main.php recursion1
php -d memory_limit=500M -d max_execution_time=60 main.php recursion2
php -d memory_limit=500M -d max_execution_time=60 main.php goto
time php -d memory_limit=500M -d max_execution_time=60 main.php object
<?php
while ($boundary--) {
$acc++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment