0

Let's say I have some code like this:

default_pos = (21,45)
#I do some more stuff now, then change my mind to change the default_pos
#So, I overwrite default_pos and assign something else to it
default_pos = (756,600)

What if instead of this I declared a new variable called default_pos_changed and left the old one just how it is? That would mean an unnecessary variable. So,wouldn't it use up a bit more memory than needed? Now, if there were hundreds of unused variables like this, it might be a problem, right?

shamilpython
  • 479
  • 1
  • 5
  • 18
  • 1
    You just changed your post to ask a completely different question :( – paulsm4 Aug 17 '18 at 05:23
  • Sorry, it was a bit unclear – shamilpython Aug 17 '18 at 05:24
  • The answer depends not on the language, but on the interpreter. `CPython`, `PyPy`, `IronPython`, ...? – Dolph Aug 17 '18 at 05:25
  • I'm using CPython, didn't like the sound of IronPython. Using CPython for over an year. Never head problems – shamilpython Aug 17 '18 at 05:26
  • Variables : Variables are known at the runtime only, unless they are global or constant. Heap memory allocation scheme is used for managing allocation and de-allocation of memory for variables in runtime. [link](https://www.tutorialspoint.com/compiler_design/compiler_design_runtime_environment.htm) – Tanmay jain Aug 17 '18 at 05:31

1 Answers1

4

What you call a variable is actually a reference to an object. So, using a new variable like default_pos_changed consumes some memory. But, only the memory to store the reference, not the object itself.

You can take a look to the C implementation of Python on GitHub. A reference is essentially a pointer (and additional info), so its size is around the size of a pointer. On 64 bit machine it 8 bytes. It’s small compared to the referenced object size.

Edit

You can use del to free the memory: the reference is deleted and if the number of references to an object is nul, the object allocated memory can be free too according to the garbage collector rules.

del default_pos_changed. # free the reference memory
del default_pos. # free the reference memory, the object can be garbage collected.
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
  • 2
    However, keeping a bunch of variables around, especially in the global scope, means that the objects they refer to won't be deallocated. Probably worth mentioning that. But yes, it is a good point that even hundres of "unecessary" variables would only take up a few kilobytes. – juanpa.arrivillaga Aug 17 '18 at 05:56
  • Thanks, I already knew about `del`, I was just curious about the variables. – shamilpython Aug 17 '18 at 07:07