Setting Variables To Nil

Is it necessary to set variables to nil when not in use?

I feel like it is necessary to act as a clean up to prevent memory problems and such but I am not exactly sure.

I would love to see peoples opinions on this and to receive some proper advice.

1 Like

Well, I don’t know that much about memory allocation, but I mean, that’d be a good habit for sure.

I usually use local variables, especially for functions or any of those scopes, so it just removes itself when the thread ends.

5 Likes

Seems like an over optimization, you’re not going to gain measurable performance with it. If you are, you might want to think about doing things a different way (as mentioned above you should be using local variables, they get garbage collected at the end of the scope they’re in).

8 Likes

You should be setting variables to nil or destroying instances that you don’t need anymore to allow them to be garbage collected. You wouldn’t want something hanging around in the memory forever or chancing a memory leak. Make sure to also use local variables and scopes (i.e. do-end blocks) - local variables in a scope will usually get GCed when all the code is ran and the scope closes/terminates, provided a variable isn’t hanging.

2 Likes

Depends what you mean by “not in use”? Variables that go out of scope will be GC’d anyway.

1 Like

You will not gain any meaningful improvements unless you’re using a ton of variables or a huge table, and you have a long wait within the same scope as your variables and they aren’t going to be used after the wait. Only then would it be a reasonable optimization.

Local variables that go out of scope (past the end of their code block) will be garbage collected, freeing any memory they were using.

1 Like

In addition to allowing garbage collection, setting variables to nil while not being used can prevent bugs. I find that local variables at the top of the file often contain a major portion of the program’s state. Depending on how large the file/program is and how messy that state gets, I’ve often caught myself testing this global state in different ways throughout my code. It is also very easy to forget what values should be at different points. Setting variables up there to nil prevents code from using it when it shouldn’t be used and sometimes helps you remember when variables are important and when they are not.

do
--local variables declared here are thrown away because of new scope
end