Fastest way to utilize file_get_contents() in PHP

DarkLight's picture

He has: 287 posts

Joined: Oct 2007

Hi guys. I'm making some performance tweaks to a custom Array cache system I built a while ago, and have a question. As it is, I use file_exists() to check if the cache file exists, before using file_get_contents() to load it. Which works very well.

But would it be faster to simply attempt the file_get_contents() straight away, and handle an empty response the same way I would handle file_exists() returning false?

I've tried both ways, and even ran some microtime() to try and find the best way. But I get inconclusive results, so here I am Smiling

<?php
if(file_exists($file)) {
$data = json_decode(file_get_contents($file), true);
}
?>

VS

<?php
$data
= @file_get_contents($file);
if(isset(
$data) && !empty($data)) {
$data = json_decode($data, true);
}
?>

Both work very well, but which is the "best" way?

Thanks in advance.

Powerful laser pointers, tactical flashlights, plasma lighters, sensory lights and more. Free worldwide shipping, PayPal secure checkout, no signup required.

https://coldcast.net