Search code examples
c#arraysperformanceoverhead

C# length 1 array versus single value, performance and memory overhead


Question:

What is the performance and memory overhead of using an array with the length of 1 instead of the value directly?

private Item[] item = new Item[1];
   vs.
private Item item;

Usage:

I have an abstract base class ItemHolder which is beeing inherited both by the SingleItemHolder and MultipleItemHolder classes. The first holding a single item as the main value while the other holds a list. To access the value I see three possibilities:

Adding two methods to the base class

public abstract Item GetItem();
public abstract Item[] GetItems(int amount);

drawback beeing the SingleItemHolder has the unnecessary method to get multiple items while having only one per definition.
Another method would be to only implement the second method and passing the single value as a length 1 array

public override Item[] GetItems()
{
    return new[] { storedItem };
}

or storing the single value as a length 1 array in the first place

private Item[] item = new Item[1];
public override Item[] GetItems()
{
    return item;
}

Both the multiple as well as the single item holders are used equally as often and quite often in general. The methods in question could very well be called dozends of times per game frame from all over the gameworld. Therefor I am wondering which version the most efficient would be, or, to be more general, what difference in overhead a length 1 array has over a single value.


Solution

  • Just a short note. In the .NET world the big performance issue is the GC that may easily lock the app for 50-100ms. You will likely not see a big difference in reading data from an object or single value array. But you will likely get a penalty if you need to create such object a lot. You certainty should avoid creating objects from the getters code.

    I think that this article may be helpful: https://michaelscodingspot.com/avoid-gc-pressure/. Also consider usage of some Profile tool to check how much time it actually takes. I prefer using the PerfView provided by MS. It may take some time to start using it, but you certainly get benefits in results.