Skip to main content
GameDev.net gamedev.net
🔒 Locked

Minor efficiency question with python

Started by Prodigal Squirrel Apr 1, 2006 at 5:57 PM 1 replies 650+ views
Original Post
Prodigal Squirrel
Prodigal Squirrel
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?
-------------------------- Alex--------------------------
Roboguy
Roboguy
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

Kylotan
Kylotan
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 disclass Test(object):    def __init__(self):        froze = False    def Freeze1():        froze = True            def Freeze2():        if froze != True:            froze = True    	print "Freeze1" 	dis.dis(Test.Freeze1)print "Freeze2"dis.dis(Test.Freeze2)


And when you run this:
---------- Python compile ----------Freeze1  8           0 LOAD_GLOBAL              0 (True)              3 STORE_FAST               0 (froze)              6 LOAD_CONST               0 (None)              9 RETURN_VALUE        Freeze2 11           0 LOAD_FAST                0 (froze)              3 LOAD_GLOBAL              1 (True)              6 COMPARE_OP               3 (!=)              9 JUMP_IF_FALSE           10 (to 22)             12 POP_TOP              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)             26 RETURN_VALUE        

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. ;)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.