dimanche 28 juin 2020

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

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.

Aucun commentaire:

Enregistrer un commentaire