Search code examples
c#arrayspropertiesgarbage-collectionheap-memory

Do array properties cause memory allocation on the heap?


Consider the following:

public class FooBar {
    public int[] SomeNumbers {
        get { return _someNumbers; }
        private set;
    }

    private int[] _someNumbers;

    public FooBar() {
        _someNumbers = new int[2];
        _someNumbers[0] = 1;
        _someNumbers[1] = 2;
    }
}

// in some other method somewhere...

FooBar foobar = new FooBar();
Debug.Log(foobar.SomeNumbers[0]);

What I am wondering is, does calling the SomeNumbers property cause a heap allocation; basically does it cause a copy of the array to be created, or is it just a pointer?

I ask because I am trying to resolves some GC issues I have due to functions that return arrays, and I want to make sure my idea of caching some values like this will actually make a difference


Solution

  • Arrays are always reference types, so yes, it is "basically returning a pointer".

    If you are trying to debug memory issues I recommend using a memory profiler. There is one built in to Visual Studio or you can use a 3rd party one (I personally like DotMemory, it has a 5 day free trial). Using a profiler will help you identify what is creating memory objects and what is keeping memory objects alive.