Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats faster file_exists or DB retrieval?

I'm currently tweaking the way our images our stored for our site. For every user I'm looking to see if they have a profile image and I"m doing this by checking to see if the file exists in their folder structure. Is this faster then storing/retrieving the name of the image in a DB table?

My current file_exists code looks like this:

$gender = ($gender == 1) ? 'female' : 'male';

$filename = SITE_ROOT . $this->img_url . $user_id . 'medium_thumb.jpg';

if (file_exists($filename)) {
    $filename = $this->img_url . $user_id . 'medium_thumb.jpg?v=' . time();
}
else {
    $filename = '/images/'.$gender.'.jpg';
}       

return $filename
like image 683
Paul Avatar asked Dec 26 '22 20:12

Paul


2 Answers

I would advise you to use file_exists() even if the filename is stored fully on the database -- this will give you a reasonable fall-back when an error results in your DB not being in sync with your filesystem. It is good to have multiple levels of error handling for this kind of thing.

Given that, the question is unnecessary, since you'd use file_exists() in either case.

Furthermore, I would recommend resisting the temptation to micro-optimise your code. Unless you're making a lot of file_exists() calls, it isn't going to be making a huge difference to the speed of your program. Trying to fine-tune your performance at this level is generally unnecessary.

If you are worried about the performance of your code, use a profiling tool such as XDebug to show you where the real performance bottlenecks are. You will have some, but I guarantee they won't be in the code you're looking at here, unless it's looping.

like image 121
SDC Avatar answered Dec 29 '22 08:12

SDC


I think the file_exists is much more faster. While using sql you have to access drivers and such, file_exists is a system action.

like image 32
Yehonatan Avatar answered Dec 29 '22 10:12

Yehonatan