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.

ColdCast boasts exciting new gadgets such as USB Plasma-Arc Lighters, High-Powered Laser Pointers, Tactical Torches and more. You get 10% off your first order and free delivery to any UK or US address. With Grade A+ security, SSL encryption, and PayPal payment, your privacy is safer than ever. Better still, no registration is required! Head over to ColdCast.co.uk and see what's on offer.
https://coldcast.co.uk