I come from a python background, where it’s often said that it’s easier to apologize than to ask permission. Specifically given the two snippets:
if type(A) == int:
do_something(A)
else:
do_something(int(A))
try:
do_something(A)
except TypeError:
do_something(int(A))
Then under most usage scenarios the second one will be faster when A is usually an integer (assuming do_something needs an integer as input and will raise its exception fairly swiftly) as you lose the logical test from every execution loop, at the expense of a more costly exception, but far less frequently.
What I wanted to check was whether this is true in C#, or whether logical tests are fast enough compared to exceptions to make this a small corner case?
Oh and I’m only interested in release performance, not debug.
OK my example was too vague try this one:
Naive solution:
return float(A) % 20 # coerse A to a float so it'll only fail if we actually don't
# have anything that can be represented as a real number.
Logic based solution:
if isinstance(A, Number): # This is cheaper because we're not creating a new
return A % 20 # object unless we really have to.
else:
return float(A) %20
Exception based solution:
try: # Now we're doing any logical tests in the 99% of cases where A is a number
return A % 20
except TypeError:
return float(A) % 20
Examples using FSOs, database connections, or stuff over a network are better but a bit long-winded for a question.
Probably not. .NET exceptions are relatively expensive.
Several .NET functions offer both variants for this reason. (
int.TryParse, which returns a success code is often recommended because it is faster thanint.Parsewhich throws an exception on failure)But the only answer that matters is what your own profiling data tells you.
If you need performance, then you need to measure, measure, measure.
Because what was fastest on my computer, with my code, with my version of the .NET framework, at this time may not be the fastest on your computer, with your code, with your version of the .NET framework at the time when you read it.