5

We use struct in C# whenever possible mainly because it is stored on the stack and no objects are created for it. This boosts the performance.

On the other hand, arrays are stored on the heap.

My question is, if I include an array as an element of the struct, something as follows:

struct MotionVector
{
    int[] a;
    int b;
}

Then what will be the consequences. Will that array be stored on stack? Or the performance advantage of using struct will be lost?

trincot
  • 317,000
  • 35
  • 244
  • 286
shahensha
  • 2,051
  • 4
  • 29
  • 41
  • 2
    http://stackoverflow.com/questions/3942721/c-structs-versus-classes – Mitch Wheat Feb 20 '12 at 10:35
  • 1
    Have you actual performance issues? See http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx – ken2k Feb 20 '12 at 10:40
  • http://stackoverflow.com/a/1114152/55209 — A excellent explanation – Artem Koshelev Feb 20 '12 at 10:40
  • @ken2k I do have performance issues. I am making a real-time gesture recognition system. Any pointed on a way to improve the logic will be highly appreciated! – shahensha Feb 20 '12 at 11:02

4 Answers4

8

Only the pointer to the array will be stored in the stack. The actual array will be stored in the heap.

Dhwanil Shah
  • 1,072
  • 1
  • 9
  • 25
1

int[] a is a reference type i.e. it references an array of integers. The 'reference' itself will be stored on the stack. However, the data it references will be stored on the heap when you do something like this:

MotionVector z;
z.a = new int[10];
Rohan Prabhu
  • 7,180
  • 5
  • 37
  • 71
1

You will hold a reference to a in your struct; that will be part of the struct on the stack.

The actual int[] object, if/when you initialize it, will go wherever it would go otherwise (the heap in most architectures).

0

If you don't want to create elements dynamically, consider to create a (big) buffer of MotionVector instances during startup and reuse those when needed. Then you will not get the penalty of creating/destructing them dynammically.

Of course you have to write some small functions to get a 'free' instance and to obtain one, use a boolean in the struct for that (or by using an interface).

To do this you could e.g.:

Create during initialisation of your app the motionvectors:

MotionVectors motionVectors;

Add a boolean to the MotionVector class:

public class MotionVector
{
    bool InUse { get; set; }

    public MotionVector() 
    {
        InUse = false; 
    }
}

Define the new class MotionVectors:

class MotionVectors
{
    MotionVector _instances[100];

    public void Free(MotionVector vector)
    {
        var index = 'search vector in _instances' 
        _instances[index].Inuse = false;
    }

    public MotionVector GetNewInstance()
    {
        var index = 'first free vector in _instances'
        _instances[index].Inuse = true;
        return _instances[index];
    }
}
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119