Reputation: 12585
Suppose I have the following python code:
a = b = 0
if f(a) and (g(b) == 1):
# Do Something #1
pass
elif f(a) and (g(b) == 2):
# Do Something #1
pass
You can assume that the functions f()
and g()
take up some non-negligible amount of CPU resource.
I want to optimize this code for computational efficiency. Should I change it to the following?
a = b = 0
if f(a):
x = g(b)
if x == 1:
# Do Something #1
pass
elif x == 2:
# Do Something #2
pass
Is there any way to automate this optimization? I hate doing it by hand throughout my entire codebase.
EDIT:
The functions f()
and g()
are completely deterministic. IE: they always return the same results if given the same input parameters. And they have no side effects outside their own stack context.
Upvotes: 1
Views: 76
Reputation: 133929
Using a single if for the f(a)
is definitely more efficient. For optimal efficiency you should store the result of expensive common sub-expressions in a variable:
if f(a):
gb = g(b)
if gb == 1:
...
if gb == 2:
...
This will execute these functions as seldom as possible
If g(b)
can also return a value that does not match any if
, then you should profile - it could be beneficial to calculate g(b)
first and see if it returned any valid value, and only then calculate f(a)
(if these are not dependent of course):
gb = g(b)
if gb in (1, 2) and f(a):
if gb == 1:
...
if gb == 2:
There is no way that any standard Python compiler could statically optimize these unlike in C/C++ where the function contents can be inlined.
Upvotes: 4