Reputation: 4440
if i've a program running on a server, which one will use more memory:
a = operation1()
b = operation2()
c = doOperation(a, b)
or directy:
a = doOperation(operation1(), operation2())
Edit:
1: i'm using CPython.
2: i'm asking this question because sometimes, i love readability in my code, so instead of writing looong sequences of operation, u just split them into variables.
Edit2:
here is the full code:
class Reset(BaseHandler):
@tornado.web.asynchronous
@tornado.gen.engine
def get(self, uri):
uri = self.request.uri
try:
debut = time.time()
tim = uri[7:]
print tim
cod = yield tornado.gen.Task(db.users.find_one, ({"reset.timr":tim})) # this is temporary variable
code = cod[0]["reset"][-1]["code"] # this one too
dat = simpleencode.decode(tim, code)
now = datetime.datetime.now() # this one too
temps = datetime.datetime.strptime(dat[:19], "%Y-%m-%d %H:%M:%S") # this one too
valid = now - temps # what if i put them all here
if valid.days < 2:
print time.time() - debut # here time.time() has not been set to another variable, used directly
self.render("reset.html")
else:
self.write("hohohohoo")
self.finish()
except (ValueError, TypeError, UnboundLocalError):
self.write("pirate")
self.finish()
as you can see there are variables that are only temporarly useful.
Upvotes: 1
Views: 64
Reputation: 1121446
Provided doOperation()
does not clear it's own references to the arguments passed in, or create more references to the arguments, until doOperation()
completes, the two approaches are exactly the same.
The latter will use less memory once doOperation()
completes, because by then the local variables of the function are cleaned up. In the first option, because a
and b
still hold references, the ref count does not drop to 0.
CPython uses reference counting to clean up any objects that are no longer used; once the reference count drops to 0 objects are automatically cleaned up.
If memory and readability are a concern, you can delete references explicitly:
a = operation1()
b = operation2()
c = doOperation(a, b)
del a, b
but remember that local variables inside a function are cleaned up automatically, so the following would also result in the a
and b
references being removed:
def foo():
a = operation1()
b = operation2()
c = doOperation(a, b)
Upvotes: 2
Reputation: 375494
Memory occupied by values will only be reclaimed when the values are no longer referenced. Just looking at the examples you gave, it's impossible to tell when those values are no longer referenced, because we don't know what doOperation does.
One thing to keep in mind: assignment never copies values, so merely assigning a value to a name won't increase the memory use.
Also, unless you have an actual memory problem, don't worry about it. :)
Upvotes: 1