• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
GraySnakeGenocide

Can someone give me the exact definition/usage of Stack/Heap and Reference Types in C#?

10 posts in this topic

I have gone through a million books, tutorials, videos, researched. And it's all still just giving me a headache.

I've read that alot of books/etc don't give a GOOD representation of what is actually happening. Meaning I am just reading junk that isn't entirely true.

As for what I seemingly don't understand, it's the whole concept of stack/heap. All I know is that its about memory management, that is it.

As for Reference Types, I was in the process of learning about this and then the whole stack/heap thing came into play and just confused the hell out of me.

http://pastebin.com/7mn2394j

I somewhat get that X is holding a reference to MyInt. It's just that the whole stack/heap thing has my head spinning.

1

Share this post


Link to post
Share on other sites
Thanks for the detailed explanations guys. I am slowly starting to understand it now (I'm not fully THERE yet). But after a few more readthroughs and such I guarantee I will start to get it. (I have a bad habit of having something stump the heck out of me, I give it a day or more, I come back, and it hits me like a ton of bricks.)

Once again, thanks guys.

0

Share this post


Link to post
Share on other sites
If I'm allowed to, I'd also like to thank the guys who took the time to write this all up -- this is a really clear explanation of the theory, and although I wasn't particularly searching for this topic, I learned something valuable today (and moreover, understood it!)

Thanks guys and OP for making this thread!
0

Share this post


Link to post
Share on other sites
Just a side point, but the wikipedia articles on the stack and the heap are both pretty great, and they have pictures.
0

Share this post


Link to post
Share on other sites
The stack, when it comes to C#, is an implementation detail. It's a thing the JIT'ter uses to optimize your code and not much more.

There are some hard and fast ( and wrong ) rules about what goes on the stack, but more specifically the rules are actually [b]what doesn't go on the stack[/b]. Namingly reference types and classes.

Value types *may* be created on the stack, as may structs, but there is actually no promise this will happen.


As to the super simple stupid explanation.


Ever been to a cafeteria where the plates are all stacked and when you go through the buffet you grab the top one? Well essentially that is what a stack is in C#. It's a chunk of memory that is set aside for ( the JIT engine to ) optimize access to certain types of variables. One of the advantages of a stack is, you know exactly where everything is, so there are no spaces and gaps and since we are dealing with value types, no unpredictability about when they will expire. This essentially means no garbage collection and very predictable locations, so no performance loss to searching or garbage collecting. This means, generally, the stack is always fastest.


Always fastest, but not always faster. Theoretically the heap can be just as fast, it all really depends on what goes on with memory. In the case of heap, instead of a stack, think of it like a giant array. As you allocate memory, "cells" of that array are used up. Eventually you use up all memory and one of two things occurs, the array is grown or garbage collection occurs, possibly both. Now as you are filling this array with memory, your performance is pretty much the same as the stack, as you are generally assigning your memory to the next top most location available.

Thing is, in time, just like your computer hardrive, this memory gets fragmented. So while the heap is continuous to start ( and therefore performing comparable to the stack ), as you allocate and free memory "holes" in the continuous array of memory locations essentially become available, so new allocations re-use old locations, or possibly are split into various different locations that have been made available. Now, when accessing your memory, you essentially don't have just a straight lookup any more, you may have multiple lookups and a search involved. Once this happens, the performance advantage of the stack becomes obvious.


Of course, as Eric Lippert said, this is all an implementation detail. You as the developer have absolutely no real control over what happens, beyond know what times explicitly will NOT be created on the stack.


The easiest ( and almost correct ) way to look at it is, the heap is memory as you generally think of it. The stack is a reserved piece of continuous memory reserved by the JIT engine for optimizing types that meet a certain criteria.




For a much more detailed explanation ( on a subject with a lot of misinformation ) from the man who is probably the second most knowledgeable person on C# read [url="http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx"]here[/url] and [url="http://blogs.msdn.com/b/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx"]here[/url].


It will basically tell you everything you needed to know.


I think a source of much of the confusion is the stack in C++, where the programmer had much more implicit control. In C# to be honest, I don't really know why they even made the distinguishment. They should have probably ignored the concept completely and made it something only the compiler developers were really aware of. Worst case scenario, for those few edge cases where the developer needed to optimize for stack usage, it could have been exposed as an attribute. Actually, there is already the stackalloc method, so even this wouldn't be need.
2

Share this post


Link to post
Share on other sites
I had to draw a picture of what the stack and the heap would look like after each line of assembly code (made by compiling some c code) was executed for a final one time.

Basically, the stack stuff goes away when the function goes out of scope - all of the variables it declares that don't use the static keyword disappear when it returns.

Stuff on the heap goes away when you release it (when you use delete or free()) or when the process gets judo chopped by the operating system.

Other than that there are some execution speed implications but the main rule is don't allocate and release stuff on the heap any more frequently than you have to (don't do it in loops or little functions that get called all the time).
-1

Share this post


Link to post
Share on other sites
[quote name='Serapth' timestamp='1319820340' post='4877904']
I think a source of much of the confusion is the stack in C++, where the programmer had much more implicit control. In C# to be honest, I don't really know why they even made the distinguishment. They should have probably ignored the concept completely and made it something only the compiler developers were really aware of. Worst case scenario, for those few edge cases where the developer needed to optimize for stack usage, it could have been exposed as an attribute. Actually, there is already the stackalloc method, so even this wouldn't be need.
[/quote]

Yes, this tripped me at first when moving from C++ (along with a few other memory related details) - the best thing for me (from a practical viewpoint) was to just forget about the hows and whys of memory in .net and trust the framework to take care of it all. I still get a twinge of, er, guilt maybe?, every now and then when tossing around a ton of instanced objects. Old habits, I suppose.

Not to say these things aren't important to know, and some of the wonderful replies here have filled in the rough spots of my understanding.
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0