Avoid IF statement after condition is met

I have a division operation inside a loop repeating many times. It so happened that in the first few passes through the cycle (more or less the first 10 cycles), the divisor is zero. Once it gets the value, a div error of zero is no longer possible.

I have an if condition to check the divisor value to avoid the div being zero, but I am wondering if there is a performance impact that this if evaluates for each run in subsequent cycles, especially since I know that it is useless.

How should this be encoded? in python?

+4
performance python if-statement
Mar 26 '10 at 6:54
source share
3 answers

I would wrap your call in try / except blocks. They are very cheap in python and cost about the same as a pass statement if no exception is thrown. Python is designed in such a way that you should make your calls and analyze any errors, and not always ask for permissions.

Code example:

 def print_divide(x,y): try: print x/y except ZeroDivisionError: pass 
+5
Mar 26 '10 at 7:13
source share
— -

Do not worry. if (a != 0) cheap.

An alternative (if you really want it) could be to split the loop into two and exit the first when the divisor gets its value. But it looks like this will make the code unnecessarily complicated (hard to read).

+9
Mar 26 '10 at 6:56
source share

I am with Tilo: I think it should be pretty cheap.

If you really don't care, you should provide a code and find out if small overheads are unacceptable. I do not suspect.

+1
Mar 26 '10 at 7:05
source share



All Articles