- Home /
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?
Answer by Kiwasi · Oct 31, 2014 at 03:19 AM
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.
That's helpful, thanks. I guess I kinda knew that, but it's good to have it verified.
If you only use the variable in a single class, then just declare it inside the method, and if you can pass a value from one method to another then you should most probably do that ins$$anonymous$$d of declaring a whole heap of global variables.
@theredace:
I'm no computer scientist either, but i can tell you for sure that you got stack and heap mixed up. The heap is a huge, well heap of memory where all objects are instantiated. So all reference types will be on the heap.
The heap is also called the "long lived storage area" (to quote Eric Lippert). There you usually store things that are going to live for a long(er) time.
The stack on the other hand could be called "short lived storage area" (Eric again). The stack is used for local variables in methods. When you enter a method, the method "reserves" as many bytes on the stack as this method needs for it's local variables. This "stack frame" is "freed" as soon as the method is finished. You might want to read about the Stack here.
local variables don't produce garbage as the stack has a fix size. If you call the same method two times in a row both will use the same memory on the stack.
Like Bored$$anonymous$$ormon said only declare variables in a class when they are required by the class itself and not by one method. If a method needs certain data, pass it as parameter. Parameters are also copied to the methods stack.
Disclaimers: Rampant generalizations ahead.
As a good best practice, you should always declare variables at the smallest possible scope that gets the job done.
In the olden times, it would be awful to do something like:
for(int i = 0; i < 10; i++)
{
SomeType obj = new SomeType();
}
Since you are creating and destroying an object every loop. But modern compilers are pretty good at optimizing thing like that away.
It also used to be that if you were creating variables with the 'new' keyword, they'd be created on the heap, and if you didn't create them with 'new' they would be on the stack.
Since C# treats everything like an object, you end up calling 'new' on everything.
When in doubt, you should trust the compiler's optimizations and the languages constructs to do what they do best. If, at the end of everything, you're noticing performance issues, hit the whole thing with a profiler and find exactly where the slow down is.
Thanks all for this info and links, I've wondered about this for a while and have been going about this in the wrong way, I'd assumed I would create garbage if I was using a method every frame and constantly creating and destroying a var, damn, thanks again!
Answer by Owen-Reynolds · Oct 31, 2014 at 07:31 PM
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.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Need help calling a script to another keep getting errors 1 Answer
Should I go with C# and Unity or C++ and Unreal/Some other engine 0 Answers