Don't try to optimize before you benchmark.
With that in mind, it is true that all expressions will be evaluated even if an intermediate term is zero.
Order may still matter. Expressions are evaluated from left to right. If a,b,c,...
are very large numbers, they could force Python to allocate a lot of memory, slowing down the calculation before it comes to j=0
. (If j=0
came earlier in the expression, then the product would never get as large and no additional memory allocation would be needed).
If, after timing your code with timeit or cProfile, you feel this may be your situation, then you could try pre-evaluating c,d,k,j
, and testing
if not all (c,d,k,j):
expression = 0
else:
expression = a*b*c*d*....*w
Then time this with timeit
or cProfile
as well. The only way to really tell if this is useful in your situation is to benchmark.
In [5]: import timeit
In [9]: timeit.timeit('10**100*10**100*0')
Out[9]: 3.2911438941955566
In [10]: timeit.timeit('0*10**100*10**100')
Out[10]: 0.33102798461914062