Sign in to follow this  
Prodigal Squirrel

Minor efficiency question with python

Recommended Posts

I recently defined, in a class, a freeze and unfreeze method. Freeze sets the objects froze variable to True, and unfreeze sets it to False. Now, is it worthwhile to check and see if the variable is already True or False, and only assign a value to the variable if it isn't?

Share this post

Link to post
Share on other sites
I would not do the test. First, it obscures the meaning of the code a bit. Second, it would not actually be more efficient (in one case of the test, it would be pretty much the same efficiency. In the other, it would be less efficient).

EDIT: Even if it was more efficient, I still wouldn't do it:

  • See my first point in my original post body.

  • It would be a micro-optimization which probably wouldn't actually have a noticable effect

Share this post

Link to post
Share on other sites
No, don't check first. That's definitely a case of premature optimization, and doubly so because this will slow your program down.

Because I am feeling charitable today, I shall prove this for the enlightenment of all. ;)

import dis

class Test(object):
def __init__(self):
froze = False

def Freeze1():
froze = True

def Freeze2():
if froze != True:
froze = True

print "Freeze1"
print "Freeze2"

And when you run this:

---------- Python compile ----------
8 0 LOAD_GLOBAL 0 (True)
3 STORE_FAST 0 (froze)
6 LOAD_CONST 0 (None)
11 0 LOAD_FAST 0 (froze)
3 LOAD_GLOBAL 1 (True)
6 COMPARE_OP 3 (!=)
9 JUMP_IF_FALSE 10 (to 22)

12 13 LOAD_GLOBAL 1 (True)
16 STORE_FAST 0 (froze)
19 JUMP_FORWARD 1 (to 23)
>> 22 POP_TOP
>> 23 LOAD_CONST 0 (None)

In the first case, you perform 4 instructions. In the second case, you perform 7 instructions if the test is false and 10 if it's true. The only way the first case could be slower is if STORE_FAST is a significantly slow instruction, and I'm guessing by the name that it is not. ;)

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this