1

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?
}
cjmarsh
  • 292
  • 2
  • 12
  • 2
    I would question the use and/or design of your `struct` in this case. Have a look here: [Why are mutable structs “evil”?](http://stackoverflow.com/questions/441309/why-are-mutable-structs-evil) – sstan Jan 16 '16 at 00:43
  • That aside, if you can avoid an allocation inside of the loop, I think that is clearly worth doing. – i_am_jorf Jan 16 '16 at 00:50
  • For your question, "How costly is it for the stack to instantiate variables, if at all?" - I would suggest you write code that does it both ways and **time** them. That's the only way to know for sure. – Enigmativity Jan 16 '16 at 01:16
  • Your second question, "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?" - is really confusing. Please try to rephrase to make it clear. – Enigmativity Jan 16 '16 at 01:17
  • 1
    @sstan The struct itself was just an example and not really the point. I was trying to get at what happens to the structs in terms of memory storage and allocation, not what happens to their values. – cjmarsh Jan 16 '16 at 01:30
  • Also, the compiler is perfectly able to detect that you're creating a local in a loop. It will use the same storage on the stack for all of the iterations. – Brian Rasmussen Jan 16 '16 at 01:30
  • @Enigmativity The second question was meant to ask if the struct gets allocated memory in the scope where the method call is when declared as a parameter. – cjmarsh Jan 16 '16 at 01:33
  • @cjmarsh - Well, from memory the parameters get pushed to the stack before the call to the method is made. – Enigmativity Jan 16 '16 at 02:49

0 Answers0