Reputation: 1269
Is it more efficient to update attributes or just instantiate a new object?
For example:
class Position(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def update_position(self, x, y, z):
self.x = x
self.y = y
self.z = z
def new_Position(self, message):
self.update_position(message[0], message[1], message[2])
def new_Position(message):
return Position(message[0], message[1], message[2])
Upvotes: 1
Views: 300
Reputation: 29302
You shouldn't do premature optimization, the choice between an update method and some sort of factory function is mainly a design choice.
Anyway, out of curiosity, here's the disassembled code between the two calls:
>>> p = Position(1,2,3)
>>> dis.dis(p.new_position)
11 0 LOAD_FAST 0 (self)
3 LOAD_ATTR 0 (update_position)
6 LOAD_FAST 1 (message)
9 LOAD_CONST 1 (0)
12 BINARY_SUBSCR
13 LOAD_FAST 1 (message)
16 LOAD_CONST 2 (1)
19 BINARY_SUBSCR
20 LOAD_FAST 1 (message)
23 LOAD_CONST 3 (2)
26 BINARY_SUBSCR
27 CALL_FUNCTION 3
30 POP_TOP
31 LOAD_CONST 0 (None)
34 RETURN_VALUE
>>> dis.dis(new_position)
2 0 LOAD_GLOBAL 0 (Position)
3 LOAD_FAST 0 (message)
6 LOAD_CONST 1 (0)
9 BINARY_SUBSCR
10 LOAD_FAST 0 (message)
13 LOAD_CONST 2 (1)
16 BINARY_SUBSCR
17 LOAD_FAST 0 (message)
20 LOAD_CONST 3 (2)
23 BINARY_SUBSCR
24 CALL_FUNCTION 3
27 RETURN_VALUE
Upvotes: 1