Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
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(). The page does involve database access - and this caching would avoid that entirely.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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;
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!