Kyle Marcus Enriquez
Kyle Marcus Enriquez

Reputation: 118

Having a list inside recursive function's impact on memory/resources

I am new to Python and I plan on having a list inside a recursive function such as

def myRecursion(a):

    A = [0,1,2]    

    #Rest of code here
    myRecursion(a-1)

My question is will having A inside the recursion create many instances of it and eat up my resources? I should also note that the contents of the list is always the same.

Upvotes: 1

Views: 58

Answers (1)

user3483203
user3483203

Reputation: 51165

A simple answer with some sample timings: Yes, creating a list inside of a recursive function will have an impact on performance, as opposed to creating it outside a recursive function and passing it in.

In [1]: def recursion1(n):
   ...:     A = [1,2,3]
   ...:     return n if n == 0 else recursion1(n-1)
   ...:

In [2]: %timeit recursion1(1000)
232 µs ± 7.84 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [3]: def recursion2(n, A):
   ...:     return n if n == 0 else recursion2(n-1, A)
   ...:

In [4]: A = [1,2,3]

In [5]: %timeit recursion2(1000, A)
163 µs ± 681 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

My question is will having A inside the recursion create many instances of it

We can use id() to check the identity of an object:

In [6]: def recursion1(n):
   ...:     A = [1,2,3]
   ...:     print(id(A))
   ...:     return n if n == 0 else recursion1(n-1)
   ...:

In [7]: recursion1(3)
129035280
134141552
129297184
134141472
Out[7]: 0

In [8]: def recursion2(n, A):
   ...:     print(id(A))
   ...:     return n if n == 0 else recursion2(n-1, A)
   ...:

In [9]: recursion2(3, A)
133702400
133702400
133702400
133702400
Out[9]: 0

Upvotes: 1

Related Questions