Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda