简体   繁体   English

了解递归调用中的Python列表内存使用情况

[英]Understanding Python List Memory Usage In Recursive Calls

I just wanted to check if I understood Python's memory management correctly. 我只是想检查一下我是否正确理解了Python的内存管理。

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. 以下函数将使用O(j)内存,但不使用 O(nj)内存,因为参数n是对列表的引用,但不是列表本身。

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. 另外,说这个函数是用C编写的,我是否正确地假设使用C,它的内存使用量将是O(nj) ,因为将为每个递归调用创建列表/数组的副本。

Yes, that is correct. 对,那是正确的。 Each recursive step will use O(1) memory: function call overhead, and one pointer for each function parameter. 每个递归步骤将使用O(1)内存:函数调用开销,以及每个函数参数一个指针。

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: 您可以通过创建一个大对象( x = "x" * 1024 * 1024 * 100 ),然后对其重复进行多次并检查进程的内存使用情况来实验性地验证这一点:

def recurse(x, n):
    if n == 0:
        raw_input("done! Check memory usage now.")
        return
    return recurse(x, n - 1)

recurse(x, 1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM