Is there any appreciable difference, in terms of speed on a low-traffic website, between the following snippets of code?
$html = file_get_contents('cache/foo.html');
if ($html) {
echo $html;
exit;
}
Or this:
$file = 'cache/foo.html';
if (file_exists($file)) {
echo file_get_contents($file);
exit;
}
In the first snippet, there's a single call to file_get_contents() whereas in the second there's also a call to file_exists(). The page does involve database access - and this caching would avoid that entirely.
CodePudding user response:
It will be unnoticeably slower on a low-traffic website; but there is no reason to perform that check anyway if you're going to get the contents if it exists, since file_get_contents()
already performs that check behind-the-scenes, returning false
if the file doesn't exist.
You can even put the call to file_get_contents()
directly inside the condition:
if ($html = file_get_contents('cache/foo.html')) {
echo $html;
exit;
}
CodePudding user response:
The runtime differences are so minimal for both variants that it does not matter in practice. The first variant is slightly faster if the file exists. The second variant is faster if the file does not exist. Both solutions do not have the best performance because the entire HTML is first loaded into memory before the output is done with echo. Better is:
$ok = @readfile ('cache/foo.html');
With readfile the file is output directly or without detours. The @ operator suppresses the warning if the file does not exist. $ok contains the number of bytes output if the output was successful and false if the file does not exist.