Thursday, 21 September 2017

TObjectList vs TObjectDictionary

When I need to store a list of objects I usually use a TObjectList (Generics.Collections), but I was speaking to another developer who uses TObjectDictionary to store a list of objects. I searched the net for when to use a TObjectDictionary instead of a TObjectList and vice-versa, but could not find any definitive answers. I decided to write a little test app to understand the difference, this simply did the following:

  • Created 1 million objects for each list and added them to the list.
  • Cleared the list of the 1 million objects.
  • Populated the list with 1 million newly created objects.
  • Found 100 objects in the list.
Below are the results, time is in ms:


ObjectList Clear - 47
ObjectList Populate - 344
ObjectList Find - 78
ObjectList Find - 78
ObjectList Find - 78
ObjectList Find - 79

ObjectDictionary Clear - 265
ObjectDictionary Populate - 579
ObjectDictionary Find - 0
ObjectDictionary Find - 0
ObjectDictionary Find - 0
ObjectDictionary Find - 0

As you can see the TObjectDictionary was slower to clear and populate the list, but was faster finding the 100 objects. This is most likely due to the TObjectDictionary being derived from TDictionary which is a hash table and is optimised for lookups.

So, generally from these results I am happy sticking with TObjectList, but if I need to store a lot of objects and also need to find a lot of objects then using a TObjectDictionary is a better choice.