Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by theredace · Oct 31, 2014 at 02:56 AM · c#stack

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
4
Best Answer

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.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image theredace · Oct 31, 2014 at 03:51 AM 0
Share

That's helpful, thanks. I guess I kinda knew that, but it's good to have it verified.

avatar image Dark_Tiger · Oct 31, 2014 at 04:03 AM 0
Share

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.

avatar image Bunny83 · Oct 31, 2014 at 05:32 AM 4
Share

@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.

avatar image Habitablaba · Oct 31, 2014 at 08:03 PM 1
Share

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.

avatar image MrSoad · Oct 31, 2014 at 10:09 PM 0
Share

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!

avatar image
2

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

28 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges