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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With