Understanding where to declare variables. Stack vs heap.

I’m finishing up my first project in Unity (C#) and I’m wondering if the standard way that I declare variables isn’t a good best practice.

Basically, if I know that I need a variable in a script, I just declare it up front (outside of any of my methods) so that I have my necessary variables or references. I rarely declare variables within my methods or functions unless I have to for some reason. As I understand it, doing it this way is allocating the memory for these variables to the “stack”, so it’s always in memory even if I don’t currently need it.

My reason for doing this was largely because as I was learning to code, I assumed that “declaring” a variable had some overhead, and I wanted to get it out of the way up front so it wasn’t impacting performance later as my scripts run. I realize now (as I learn more) that this isn’t really the case, but I’m trying to understand what the best practices are for this. Is there a general rule of thumb for when I should allocate a variable up front to the stack, vs. when I should only allocate them within my methods and functions (on the heap)? From my research on this it seems like reference type variables should go on the stack, and value type variables that don’t need to be persistent over time in some way should go on the heap.

Assuming I don’t have any memory consumption issues (my project uses very little memory), am I doing this wrong by just putting everything on the stack?

I have a feeling you are getting the meaning of stack and heap mixed up here. I’m no computer scientist, so I won’t attempt to educate you, my understanding might be wrong.

However I can help on declaring class scope versus local scope variables.

Declare class variables for anything that needs to persist with the class.

Declare local scope for everything else.

This is really an optimization question: “should I write my program in some strange, hard-to-read way, so it runs faster?” The answer is almost always, no. Just write the program which-ever way it seems to make the most sense.

Most people think it looks better to declare variables just before you use them.

If you’re interested in reasons why not to think about speed-up tricks, just google “premature optimization.”

Roughly, if you use every cute speed-up trick, your program will take twice as long to write and might run 1% faster. It will probably run slower, since the exact way the tricks work makes them easy to use wrong. And, most real speed-ups are big-picture design changes, not little tricks.