1

Everyone was telling me that a List is heavy on performance, so I was wondering is it the same with a dictionary? Because a dictionary doesn't have a fixed size. Is there also a dictionary with a fixed size, just like a normal array?

Thanks in advance!

anonymous-dev
  • 2,897
  • 9
  • 48
  • 112
  • 1
    Worth reading is [this semi-related Stack Overflow question](http://stackoverflow.com/questions/8307222/dictionary-list-or-array) on Dictionaries, Lists, and arrays. The accepted answer mentions both speed (of random item access) and memory concerns for each option. – Serlite Sep 18 '15 at 15:40

3 Answers3

1

This is depends on your needs.

If you just add and then iterate items in a List in sequental way - this is a good choice.

If you have a key for every item and need fast random access by key - use Dictionary.

In both cases you can specify the initial size of the collection to reduce memory allocation.

Skyblade
  • 2,354
  • 4
  • 25
  • 44
1

A list can be heavy on performance, but it depends on your use case.

If your use case is the indexing of a very large data set, in which you plan to search for elements during runtime, then a Dictionary will behave with O(1) Time Complexity for retrievals (which is great!).

If you plan to insert/remove a little bit of data here and there at runtime then that's okay. But, if you plan to do constant insertions at runtime then you will be taking a hit on performance due to the hashing and collision handling functions.

If your use case requires a lot of insertions, removals, iteration through the consecutive data, then a list would be and fast. But if you are planning to search constantly at runtime, then a list could take a hit performance-wise.

Regarding the Dictionary and size:

If you know the size/general range of your data set then you could technically account for that and initialize accordingly. Or you could write your own Dictionary and Hash Table implementation.

In all:

Each data structure has it's advantages and disadvantages. So think about what you plan to do with the data at runtime, then pick accordingly.

Also, keeping a data structure time and space complexity table is always handy :P

Eissa
  • 700
  • 5
  • 17
0

If you have a varying number of items in the collection, you'll want to use a list vs recreating an array with the new number of items in the collection.

With a dictionary, it's a little easier to get to specific items in the collection, given you have a key and just need to look it up, so performance is a little better when getting an item from the collection.

List and dictionary are part of the System.Collections namespace, which are mutable types. There is a System.Collections.Immutable namespace, but it's not yet supported in Unity.

user3071284
  • 6,955
  • 6
  • 43
  • 57