Jump to content
  • Advertisement
Sign in to follow this  
Prodigal Squirrel

Minor efficiency question with python

This topic is 4488 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!