I can't figure out why function f1 uses the same amount of memory as function f2:
from memory_profiler import memory_usage
class BigObject(object):
def __init__(self):
self.value = "a"*1000000
a = []
def p1(n):
if n == 0:
return
a.append(BigObject())
p1(n-1)
a.pop()
def p2(n, p):
if n == 0:
return
p2(n-1, p + [BigObject()])
def f1():
p1(200)
def f2():
p2(200, [])
mem_usage = memory_usage(f1)
print('Memory usage (in chunks of .1 seconds): %s' % mem_usage)
print('Maximum memory usage of f1: %s' % max(mem_usage))
mem_usage = memory_usage(f2)
print('Memory usage (in chunks of .1 seconds): %s' % mem_usage)
print('Maximum memory usage of f2: %s' % max(mem_usage))
Output:
Memory usage (in chunks of .1 seconds): [28.2421875, 28.55078125, 57.859375, 88.734375, 119.375, 150.7890625, 182.2109375, 213.62890625, 64.45703125, 28.2421875]
Maximum memory usage of f1: 213.62890625
Memory usage (in chunks of .1 seconds): [152.25390625, 152.25390625, 152.25390625, 152.25390625, 152.25390625, 152.25390625, 152.25390625, 177.328125, 209.73046875, 151.296875]
Maximum memory usage of f2: 209.73046875
My thought was that since p2 is continually building temporary lists due to the "+" operator which creates a new list every function call, surely it should be using more memory compared to p1 which only modifies one list, but this was not born out by the observation.
What's going on?