I know that structs are value types and live on the stack, unless declared as a field in a reference type, and that they contain their values in memory at that location. What I'm wondering is whether or not it is efficient or worthwhile to re-use a declared struct in an iterated loop rather than creating a new one each time. How costly is it for the stack to instantiate variables, if at all? Also, as a somewhat related question, if I were to instantiate a struct inside a method call does it create a local copy of the struct or create it first as the parameter of the method when it executes?
About the declarations:
// Is this worth doing...
MyStruct ms = new MyStruct(0);
for (int i = 0; i< 10000; i++)
{
ms.num = i;
// Do something with ms
}
// ...over this:
for (int i = 0; i< 10000; i++)
{
MyStruct ms = new MyStruct(i);
// Do something with ms
}
public struct MyStruct
{
public int num;
public MyStruct(int myNum)
{
num = myNum;
}
}
And the instantiation:
for (int i = 0; i< 10000; i++)
{
MyMethod(new MyStruct(i));
// Does the MyStruct live in scope?
}