Is it Rational to use dictionary rather than enum and array?

Hi all. Suppose we have an array of components(collection) and an enum that defines them. So we can access to them easily using “components[(int)Eenum.enumName]” but it can create problems when we want to add new component to the collection array.We must care about placing it correctly to the array index (in the inspector) and add a new enum element and assign correct number to it.
The other solution is to use dictionary.It can solve the problems but it is slower. Do you use a dictionary or an array and enum?

I’m planning on using a dictionary because you can access them from strings, which are easy to save and retrieve. I don’t know how good it will work, it just sounds like an easy way to do saves. I haven’t experimented with it yet.

I was thinking of, for quests, you have all kinds of booleans for , been to this place, did this, got that. A dictionary would be one place to store them all and retrieve them.

1 Like

You could have both a dictionary and a list cache. Use the dictionary for indexing, and list for iterating.

After updating the dictionary, create the list using dictionary.Values.ToList() (requires System.Linq).

1 Like

yes it is perfect to use a dictionary for indexing and when we want to iterate all of them use list or array

I’ve seen the Enum implementation before, and there was always an implementation that would’ve been cleaner and more intuitive. plus having to go back and add a new enum and recompile every time you want to add a new component gets tiresome.

If you are using enums it sounds like the size of the collection is relatively small, so performance isn’t really the issue here.

Thank you but it can cause a problem when you add and specially remove an enum element. So you need to change all array elements and sort them again

[SerializeField]
Item[] itemArray;

public enum EItemType{
None=-1,item1,item2,item3
}

itemArray[(int) itemType]

Assume you remove item2, so you need to change and sort again itemArray from the inspector and care about indexing

yes it was a comparison between array and dictionary and not enum

JoshuaMcKenzie is agreeing with you, especially the adding and removing bit.

Their final statement about performance means that Dictionary vs Array is indistinguishable at this level, so might as well go with what’s easier to use… in your case, you seem to want to use Dictionary, so use it.

2 Likes