简体   繁体   English

如何编写文件检查代码以获得最佳性能

[英]How to write file checking code for best performance

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().在第一个片段中,有一个对 file_get_contents() 的调用,而在第二个片段中,还有一个对 file_exists() 的调用。 The page does involve database access - and this caching would avoid that entirely.该页面确实涉及数据库访问 - 这种缓存将完全避免这种情况。

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.但是,如果您要获取内容(如果内容存在),则没有理由执行该检查,因为file_get_contents()已经在幕后执行该检查,如果文件不存在则返回false

You can even put the call to file_get_contents() directly inside the condition:您甚至可以直接在条件中调用file_get_contents()


if ($html = file_get_contents('cache/foo.html')) {
    echo $html;
    exit;
}

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.这两种解决方案都没有最好的性能,因为在 output 完成回显之前,整个 HTML 首先加载到 memory 中。 Better is:更好的是:

$ok = @readfile ('cache/foo.html');

With readfile the file is output directly or without detours.用readfile直接或不走弯路,文件就是output。 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. $ok 包含字节数 output 如果 output 成功,如果文件不存在则为 false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM