I'm developing a game using XNA and C# and was attempting to avoid calling new struct()
type code each frame as I thought it would freak the GC out. "But wait," I said to myself, "struct is a value type. The GC shouldn't get called then, right?" Well, that's why I'm asking here.
I only have a very vague idea of what happens to value types. If I create a new struct within a function call, is the struct being created on the stack? Will it simply get pushed and popped and performance not take a hit? Further, would there be some memory limit or performance implications if, say, I need to create many instances in a single call?
Take, for instance, this code:
spriteBatch.Draw(tex, new Rectangle(x, y, width, height), Color.White);
Rectangle in this case is a struct. What happens when that new Rectangle is created? What are the implications of having to repeat that line many times (say, thousands of times)? Is this Rectangle created, a copy sent to the Draw method, and then discarded (meaning no memory getting eaten up the more Draw is called in that manner in the same function)?
P.S. I know this may be pre-mature optimization, but I'm mostly curious and wish to have a better understanding of what is happening.
When a new struct is created, it's contents are put straight into the location where you specify - if it's a method variable, it goes on the stack; if it's being assigned to a class variable, it goes inside the class instance being pointed to (on the heap).
When a struct variable is copied (or, in your case, passed to a function), the bytes making up the struct are all copied to the correct place on the stack or inside the class (if you're setting a field or property on an instance of a reference type).
Even though there may be copying of bytes, the JIT compiler will likely optimize all the unneccessary copies away so that it executes as fast as possible. Generally, it's not something you need to worry about - this is very much a micro-optimization :)
Does this answer your question?
While value types go on the stack, there's still performance implications to allocating and deallocating all that memory every frame -- especially on the Xbox 360. On a PC you'll likely not notice the difference, but on the 360 you probably will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With