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.
Itemis a struct, then adding another pointer to this adds a small amount of overhead. If you are looking to avoid returning a value type (such as a struct), look intorefreturns: learn.microsoft.com/en-us/dotnet/csharp/programming-guide/…