0

Does Python do any analysis to free memory earlier? For example, if I have:

d = some big array
# ... use(d) ...

# no d is used from here
# a lot of other code, the code could use more big arrays

When does python decide to delete the memory used by d?

If I use d in a function, will d be freed when the function is done?

Maybe in general this is hard, because d can be assigned to others, and they may continue using d after the function is finished.

However, I was looking for some good practice that can keep python use less memory...

martineau
  • 119,623
  • 25
  • 170
  • 301
Joe C
  • 2,757
  • 2
  • 26
  • 46
  • 1
    Use `del d` when you won't be using `d` anymore. – nsilent22 Jun 08 '17 at 20:06
  • 1
    @nsilent22 It just dereference the name `d` but won't actually delete the array from memory (unless it was the only reference). – Ted Klein Bergman Jun 08 '17 at 20:07
  • 1
    Like many languages, Python uses a garbage collector. But the details of garbage collection are implementation defined. Most implementations that I know of use reference counting, so like @nsilent22 mentioned, using `del` can remove references to objects, making them eligible to be GC'd. – 0x5453 Jun 08 '17 at 20:08
  • Garbage collector handles it. See how it works https://www.quora.com/How-does-garbage-collection-in-Python-work – Priyesh Kumar Jun 08 '17 at 20:08

2 Answers2

0

You can use in your case del d to dereference the array when you are finished with it, but Python will take care of the memory itself after your program is finished running. I found 2 other questions that are similar and may delve deeper into memory management in python here are the links:

How can I explicitly free memory in Python?

and its answer:

https://stackoverflow.com/a/1316793/6475414

and:

Releasing memory in Python

Dorilds
  • 418
  • 1
  • 7
  • 15
0

Just to add a bit to the situation when d is used in function, it depends on when d is declared. If d is declared within the function, and there is no inner function referencing d, it will be garbage collected.

for example:

def outer():
     d = np.arange(10000)
     def inner():
         d += 1
         return d
     return inner

in this case d will still reside in the memory if after outer() function is returned.