如果我有一个程序在服务器上运行,哪个程序会使用更多内存:
a = operation1()
b = operation2()
c = doOperation(a, b)
或直接:
a = doOperation(operation1(), operation2())
编辑:
1:我正在使用 CPython。
2:我问这个问题是因为有时,我喜欢代码的可读性,所以不用编写冗长的操作序列,而是将它们拆分为变量。
编辑2:
完整代码如下:
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()
如您所见,有些变量仅暂时有用。
最佳答案
提供的doOperation()
不会清除它自己对传入参数的引用,或者创建更多对参数的引用,直到doOperation()
完成后,两种做法完全一样。
一旦 doOperation()
完成,后者将使用更少的内存,因为那时函数的局部变量已被清除。在第一个选项中,由于 a
和 b
仍然保留引用,因此引用计数不会降至 0。
CPython 使用引用计数来清理不再使用的任何对象;一旦引用计数下降到0,对象就会被自动清理。
如果内存和可读性是一个问题,您可以显式删除引用:
a = operation1()
b = operation2()
c = doOperation(a, b)
del a, b
但请记住,函数内的局部变量会自动清除,因此以下操作也会导致 a
和 b
引用被删除:
def foo():
a = operation1()
b = operation2()
c = doOperation(a, b)
关于python - 我会赋值还是直接在其他变量中使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14775037/