2

Is there a conceptual reason why a dictionary is preferred over a 2-entry tuple or an object with two properties?

Dictionary<int, string> userIdAndNames = new Dictionary<int, string>();

vs

List<Users> users = new List<Users>();

Where Users is defined as:

public class Users
{
    public int UserId { get; set; }
    public string UserName { get; set; }
}
Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
Daniel Kempner
  • 415
  • 5
  • 14
  • Ease of use. It avoids the need to define a new type for every simple key:value relation that doesn't require additional logic built in. – jmsb Feb 08 '14 at 20:01
  • Because the the dictionary key is placed in hash buckets for fast retrieval. – paparazzo Feb 08 '14 at 20:03
  • Can you explain what you mean by "conceptual"? Since you don't seem concerned with the implementation details and performance, what are you concerned with? The conceptual difference is that one is looked up by ordinal index, the other is looked up by key (could be a number, could be a string, could be a blob of data) – Erik Funkenbusch Feb 08 '14 at 20:59

1 Answers1

6

To do look ups using a UserId with the List<User>, you have to iterate over half the list on average to find the matching user. The number of operations is proportional to the size of the List.

When using the Dictionary on average, you only have to do a constant number of operations with respect to the number of entries in the Dictionary. Read more about the algorithm that powers a dictionary on Wikipedia.

joseph
  • 2,429
  • 1
  • 22
  • 43
  • Thanks for your response. I assumed that there was a performance penalty for using lists of objects, but is there any conceptual difference between the two? – Daniel Kempner Feb 08 '14 at 20:08
  • My apologies! Performance is the first thing that comes to my mind when I see a Dictionary. The article that the community provided is way more comprehensive than my response. It goes well beyond performance. – joseph Feb 08 '14 at 20:20