Would doing the following be faster or slower than just an if statement?
mult = x or y
# Assuming python considers something
# being "0" as false and something being 1 or higher
# (or -1 and lower) as true
mult = (x/x) or (y/y)
# This is in the case Python doesn't do what was
# described above
draw(x, y, 0, 255, 0, 255*mult)
# draw(x_pos, y_pos, red, green, blue, alpha)
Not sure how to word this better, let alone if wording it better is necessary. Just something I am curious about as I was talking about optimizing code for performance, and such an idea had come to me but wasn’t sure about since Google wasn’t providing any helpful results (all were unrelated).
I probably could test this in my own time too, but I feel as if asking someone who would know how computers would work with comparisons vs if statements could be the most helpful.
>Solution :
Python converts its operators into method calls. It doesn’t know what any of them actually do. The exact rules can get complicated, but more or less, mult = x or y
turns into
mult = x.__bool__() or y.__bool__()
x
and y
decide what bool
means to them and return True
or False
accordingly. For integers, 0
is False
, everything else is True
. or
short-circuits so if x
is True
, the y
method call is not made.
mult = (x/x) or (y/y)
turns into something like
mult = x.__div__(x).__bool__() or y.__div__(y).__bool__()
x/x
will almost aways be 1
(at least for integers) but python doesn’t know that. It needs to make the extra div
call. That makes it slower. It would be faster to write this as mult = 1 or 1
, or even better, mult = 1
. The exception is when a value is 0
as you would get a ZeroDivisionError
.
draw(x, y, 0, 255, 0, 255*mult)
vs draw(x_pos, y_pos, red, green, blue, alpha)
The first uses literals which are a bit faster than looking up and reading the variables red
, etc… But it has the cost of the multiplication. 1 will be trivially faster.
None of these different ways of doing things will make a real difference to the execution of the code IMHO. Its all a bit of white noise.