Python3: what are faster, nested function calls or if statements (try/excepts are pretty fast)

Viewed 98

In python3, let's say I got a situation where I need a integer. Is it faster to do something like

processed_number = int(round(float(some_input)))

or should I do this:

if some_input is int:
    processed_number = some_input
else:
    processed_number = int(round(float(some_input)))

or perhaps

try:
    some_statement_taht_needs_int(some_input)
# except TypeError:
#    processed_number = int(round(float(some_input)))
#    some_statement_taht_needs_int(some_input)
# Apparently, it's better to cut down on exception handling: I might handle something the wrong way
except ValueError:
    # The same thing
    processed_number = int(round(float(some_input)))
    some_statement_taht_needs_int(some_input)

I'm sorry if that was a dumb question since both use function calls. I'm just wondering if there is a significant time difference between each method. I know I shouldn't be optimizing python code too much but this is just a question (a possibly dumb one) that I had for a long time. Please don't burn me down if this is dumb.


I'm not really making code that needs this optimization (for now); this is just a question so I can improve my code in the future.

1 Answers

Usually you would not expect to be doing this so often that it is a dominant performance issue. You are likely to have some other part of your code that is the performance limiting factor.

It is usually best to code these things in the way that is cleanest and is most obvious for the next person who looks at your code to understand. Do not get hung up on premature optimization. Unless it is something that is extremely obviously slow and will happen a lot, just write your code the cleanest and clearest way. If necessary afterward you find it is slow, you can profile it to find out where it is slow and fix that.

You will usually find these kinds of things are not where the issues lie.

Related