Skip to content

Instantly share code, notes, and snippets.

@caramelchocolate
Created May 7, 2020 06:18
Show Gist options
  • Save caramelchocolate/34abba6b535cc20271c70516901931bb to your computer and use it in GitHub Desktop.
Save caramelchocolate/34abba6b535cc20271c70516901931bb to your computer and use it in GitHub Desktop.
include vs ob_get_clean benchmark
<?php
$time = microtime(true);
register_shutdown_function(
function () use ($time) {
$time = microtime(true) - $time;
$format = <<<EOD
Memory: %s / %s MB
Time: %f ms
EOD;
fwrite(STDERR,
sprintf($format,
round((memory_get_usage() / pow(1024, 2)), 4),
round((memory_get_peak_usage() / pow(1024, 2)), 4),
($time * 1000)));
}
);
$a = function() {
include 'index.php';
};
$a();
?>
<?php
makehtml(10000);
echo 'include.php' . PHP_EOL;
echo shell_exec('php include.php > /dev/null');
echo PHP_EOL;
echo 'ob_get_clean.php' . PHP_EOL;
echo shell_exec('php ob_get_clean.php > /dev/null');
function makehtml($max_row) {
$file = './index.php';
if (file_exists($file)) {
unlink($file);
}
$data = <<<'EOD'
<html>
<body>
EOD;
file_put_contents($file, $data, FILE_APPEND);
for ($i=0; $i<$max_row; $i++) {
$data = '<p>' . bin2hex(openssl_random_pseudo_bytes(64)) . '</p>' . PHP_EOL;
file_put_contents($file, $data, FILE_APPEND);
}
$data = <<<'EOD'
</body>
</html>
EOD;
file_put_contents($file, $data, FILE_APPEND);
}
?>
<?php
$time = microtime(true);
register_shutdown_function(
function () use ($time) {
$time = microtime(true) - $time;
$format = <<<EOD
Memory: %s / %s MB
Time: %f ms
EOD;
fwrite(STDERR,
sprintf($format,
round((memory_get_usage() / pow(1024, 2)), 4),
round((memory_get_peak_usage() / pow(1024, 2)), 4),
($time * 1000)));
}
);
$a = function () {
ob_start();
include 'index.php';
$output = ob_get_clean();
echo $output;
};
$a();
?>
@caramelchocolate
Copy link
Author

$ php -v
PHP 7.4.5 (cli) (built: Apr 23 2020 02:25:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.5, Copyright (c), by Zend Technologies

$ php main.php 
include.php
Memory: 1.6771 / 4.3178 MB
Time: 4.522085 ms

ob_get_clean.php
Memory: 1.6779 / 4.334 MB
Time: 5.183935 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment