I just wanted to check if I understood Python's memory management correctly.
The following function would use O(j) memory, but not O(nj) memory, since the parameter n is a reference to the list, but not the list itself.
def cool(n,j):
if j == 0:
return
return cool(n,j-1)
Also, say this function was written in C, am I correct in assuming that, with C, its memory usage would be O(nj) , since a copy of the list/array would be created for each recursive call.
Yes, that is correct. Each recursive step will use O(1) memory: function call overhead, and one pointer for each function parameter.
You can experimentally verify this by creating a large object ( x = "x" * 1024 * 1024 * 100
), then recursing on it a number of times and checking the process's memory usage:
def recurse(x, n):
if n == 0:
raw_input("done! Check memory usage now.")
return
return recurse(x, n - 1)
recurse(x, 1000)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.