Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it faster to check a file's existence prior to loading, or to catch the exception when it doesn't exist?

I have been recommended to use the second, try-except variant, but I would also like to know what others think: which procedure of the two below (if any) is more time-efficient?

procedure LoadImage(img: TImage; filename: string);
begin
  if fileexists(filename) then
    img.Picture.Loadfromfile(filename)
  else
    img.Picture.Loadfromfile('default.jpg')
end;

or

procedure LoadImage(img: TImage; filename: string);
begin
  try
    img.Picture.Loadfromfile(filename)
  except
    img.Picture.Loadfromfile('default.jpg')
  end
end;
like image 971
BogdyBBA Avatar asked Aug 10 '12 12:08

BogdyBBA


2 Answers

Forget efficiency. Code readability is way, way more important. Premature optimization is the root of all sorts of evil.

The first one is clear in its intentions. Everyone can easily figure out what is up.

The second one makes me stop and go "What the....?"

You never want your code to cause the second reaction.

like image 163
Nick Hodges Avatar answered Oct 16 '22 17:10

Nick Hodges


If time efficiency is your only criteria, first one will be faster because exception handling is CPU consuming.

FileExists() uses one WinApi call so its fast but it checks only if file exists. If file exists but its in wrong format or its blocked by other thread you will get unhandled exception.

like image 39
Jarek Bielicki Avatar answered Oct 16 '22 19:10

Jarek Bielicki