[Gambas-user] if-else vs try who are best faster in machine time?

Tobias Boege taboege at ...626...
Tue Nov 5 19:21:50 CET 2013


On Mon, 04 Nov 2013, Sebastian Kulesz wrote:
> On Mon, Nov 4, 2013 at 6:43 PM, Jussi Lahtinen <jussi.lahtinen at ...626...>wrote:
> 
> > Why not simply write benchmark?
> >
> 
> A benchmark wouldn't be accurate, as it will be IO bound, and being an old
> machine, better reduce disk IO than CPU usage (I'm guessing it uses IDE
> drives; which have low access time too). Besides, first option can fail if
> you don't have write access to the file, thus needing a third access to
> check for permission to delete.
> 

Yeah, may I throw in some related thought?

I know you asked for the most efficient way to do it but your program should
also be safe from race conditions, right? When you do

' Check for existance
If Exist(sPath) Then Kill sPath

or even

' Check for existance and write access using short-circuit
If Exist(sPath) And If Stat(sPath).Auth Like "?w*" Then Kill sPath

there is the risk (race condition) that sPath gets unlinked just at the
point Gambas is passing the "Then" keyword. So the program might think that
it is safe to remove the file without error check but the file just doesn't
exist anymore when the program is ready to delete it.

If you don't have a CATCH block in/above your function (or a Static Public
Application_Error()), the interpreter will notice the error from the kernel
and abort your program! Try Kill is always the safe way because you get an
atomic error check here.

Let's also consider what most probably happens at least under Linux when you
have Try Kill sPath in Gambas (note that I didn't consult the real sources
here, just guessing how it would be done): the interpreter will call the
unlink() syscall which deletes the file or delivers an error. The error is
propagated but suppressed by Try.

With Exist(sPath) Then Kill sPath, the interpreter likely executes something
like access() which can equivalently well fail or succeed. If it succeeds
you still have to do the same unlink() operation.

So, the best case you can get is that Exist() is false. Then the running
time is roughly access() vs. unlink(). In all other cases, the Try Kill
approach seems to be faster and safer, too.

You have to decide now: Do you expect sPath non-existing most of the time?
Do you want to ignore race conditions in favour of performance? Then use the
If Exist(...) Then Kill ... method.

Regards,
Tobi

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk




More information about the User mailing list