Since structs are value-types, their data is copied when passed into a method as an argument. Example:
int someInt = 7;
DoSomeMethod(someInt); // <-- This is passing the "value" 7.
So far, easy to understand, and you’re probably wondering how my question is valid… so consider the following:
public struct TimmysStructOfGoodness
{
public int SomeInt1;
public int SomeInt2;
public int SomeInt3;
// ... later that day ...
public int SomeInt999;
}
and then, with reference to the following code:
TimmysStructOfGoodness someStructOfGoodness = new blah blah blah...
DoSomeMethod(someStructOfGoodness); // <-- **HERE IS WHERE THE QUESTION APPLIES!**
Does the above statement try to allocate several megs of ram to “copy” my value-type (struct)?
If the answer is yes – then when/where is the line between “faster” and “slower”?
If no – then why not? Because what I know of value-types, this should be a problem.
MAJOR DISCLAIMER: I know that this has nothing to do with why you would use a struct verses a class, and I know that I will never make a struct with 999 fields – this is just a question of underlying internals and guts and the like 🙂
(updated, thanks to contributions from other users)
Unlike class, struct is created on stack. So, it is faster to instantiate (and destroy) a struct than a class.
Unless (as Adam Robinson pointed out) struct is a class member in which case it is allocated in heap, along with everything else.
On the other hand, every time you assign a structure or pass it to a function, it gets copied.
I don’t think there’s a hard limit for a struct size. Thousands of bytes is definitely too much. MSDN says:
This is – if you need to pass it by reference make it a class, regardless of the size.On the second thought, you can still pass struct by reference simply by specifying ref in the function parameter list.
So, a large struct can actually be ok if you pass it by reference and use as a class member.