Reputation: 1877
Assume we have a function which wants to operate some actions on attribute z of objA. objA is a property of objB and objB is a property of objC etc... which of these two approaches is faster ? Is there any difference?
Approach 1: Using objC.objB.objA.z
for every statement in the function.
Approach 2: Assigning a local variable like x in function as:
x=objC.objB.objA.z
then operate on x, then assign the output to the preferable variable.
I know Approach 2 makes it easier in terms of writing the actual code but doesn't defining a new variable cost more memory? Which approach is more pythonic and is there any other (better) way to do things other than aforementioned approaches?
Upvotes: 1
Views: 104
Reputation: 251365
Approach 2 will in general be quicker, although it may not be a noticeable difference unless it's in a tight loop.
Every time you do a.b.c.d
, Python has to look up the values of those attributes, even if they don't change in between uses. If you create a variable x
for that value once, then Python only has to look up the attributes once, saving time.
Doing x = a.b.c.d
does not create a new object, so it doesn't use any memory. x
will be a reference to the same object that a.b.c.d
pointed to. However, because of this, you do need to be careful. Any operations that mutate x
will affect the original object. For instance, if a.b.c.d
is a list, and you do x = a.b.c.d
, then x.append(1)
will alter the value of the original a.b.c.d
object. If this is what you want, great. If not, be sure to explicitly copy the value.
Upvotes: 4
Reputation: 133514
The 2nd one is more pythonic and it will also be faster if you are reusing objC.objB.objA.z
many times because it avoids having to do those 4 lookups each time. It isn't costly to bind this value to x
, Python simply uses the same reference to the object and will not copy it.
Upvotes: 2