1

Wondering what is faster and/or what is better practice when checking a variable in an if statement and then using it again after the if statement.

Like

if var_A + var_B > 10:
    var_C = var_A + var_B

or

 var_temp = var_A + var_B
 if var_temp > 10:
           var_C = var_temp

sorry for the bad examples, was just wonder which of these is better

1
  • 3
    Would var_C be set to anything else if the test failed? Or is it left unbound? Commented Aug 20, 2015 at 18:08

3 Answers 3

3

The third option, my favorite, would be to set it and check for untruthy to set var_C to some fallback

var_C = var_A + var_B
if var_C <= 10:
    var_C = None

no extra variable needed

Sign up to request clarification or add additional context in comments.

Comments

3

Certainly the second version is better:

  • It's faster. The expression is calculated only once.
  • It's easier to refactor. You will change the expression only in one place.
  • It's more readable. The temporary variable name can tell the meaning of the expression.

3 Comments

What if the temp var is a very large string or it gets called allot does it create allot of temp variables in memory or do they get cleaned quick? sorry for not having a concrete question or example, im just wondering how it works
temp_var and var_C refer to the same object, so it doesn't really matter.
@Tricky if you don't store the expression result in a variable it gets garbage collected after the comparison and then again created under a different reference.
0

Your second option is the best. Subjectively speaking, it's much easier for the next guy to read and maintain.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.