I have a code which has a term in a summation like:


where func[M] is a time consuming numerical integral with a parameter M. I am looping over different values of M.

My question is, does Mathematica evaluate func[M] even if the KroneckerDelta[M,0] evaluates to 0 (i.e. when M != 0)? Or does it recognize that since the KroneckerDelta[M,0] is giving 0, so the product must be zero and hence doesn't actually evaluate the func[M] part then?

Because if it is evaluating the time consuming numerical integral in func[M] anyway, I feel using an If[M=0] like statement would save computation time...? Right?


  • $\begingroup$ This Table[KroneckerDelta[1, M] Pause[M], {M, 1, 3}] // AbsoluteTiming takes six seconds. $\endgroup$
    – corey979
    Commented Mar 13, 2020 at 1:24
  • $\begingroup$ To clarify: Times in Mathematica does not short-circuit multiplication by zero. Indeed, it cannot since Times has no HoldAll attribute. This means that all it's arguments must be evaluated before Times does anything at all. Compare this with And and Or, which DO have the the HoldAll attribute and will short-circuit the moment they encounter False / True respectively. $\endgroup$ Commented Mar 13, 2020 at 11:42
  • $\begingroup$ @SjoerdSmit Gotcha. Thanks. Makes sense. Thanks, everyone! $\endgroup$
    – odomosis
    Commented Mar 14, 2020 at 22:37

1 Answer 1


We can find out easily enough:

func[x_] := Pause[1];
Table[KroneckerDelta[M, 0]*func[M], {M, 0, 10}] // AbsoluteTiming
Table[If[M == 0, func[M]], {M, 0, 10}] // AbsoluteTiming

The first one takes 11 seconds, the second one takes 1 second. So in the one with the KroneckerDelta, it is evaluating the func for each value of M whereas the If[ ] construct only evaluates the func when M=0.

  • $\begingroup$ Can you clarify what happens as it gets larger? $\endgroup$ Commented Mar 13, 2020 at 1:53
  • $\begingroup$ Thanks a ton for the response. I guess, then a general rule would be to use If[] over KroneckerDelta[] for numerical computations....? $\endgroup$
    – odomosis
    Commented Mar 14, 2020 at 22:32
  • 1
    $\begingroup$ @odomosis -- I would imagine that it depends on context, but yes, in this case you are wasting computation to compute things that you know are going to eventually be multiplied by zero! $\endgroup$
    – bill s
    Commented Mar 14, 2020 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.