I generally use List<T>
for collections.
But if I need a fast lookup on a collection, then e.g. in the following example I would use a Dictionary so I could look it up quickly by id
:
Dictionary<int, Customer>
But since I can use LINQ to query the List<T>
anyway, as below, is there any reason to go through the trouble of using a Dictionary instead of a List? Is Dictionary faster or is LINQ doing something behind the scenes that makes it just as fast?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>()
{
new Customer { Id = 234, FirstName = "Jim", LastName = "Smith" },
new Customer { Id = 345, FirstName = "John", LastName = "Thomas" },
new Customer { Id = 654, FirstName = "Rick", LastName = "Ashton" },
new Customer { Id = 948, FirstName = "Rod", LastName = "Anders" }
};
var customer = (from c in customers
where c.Id == 654 select c).SingleOrDefault();
Console.WriteLine(customer.Display());
Console.ReadLine();
}
}
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
internal string Display()
{
return String.Format("{0}, {1} ({2})", LastName, FirstName, Id);
}
}
}
A dictionary is 6.6 times faster than a list when we lookup in 100 items.
Of course the Dictionary in principle has a faster lookup with O(1) while the lookup performance of a List is an O(n) operation. The Dictionary map a key to a value and cannot have duplicate keys, whereas a list just contains a collection of values. Also Lists allow duplicate items and support linear traversal.
If you are going to get elements by positions (index) in the array then array will be quicker (or at least not slower than dictionary). If you are going to search for elements in the array than dictionary will be faster.
LINQ is absolutely 100% slower You are going to essentially "stall-out" if you are performing any complex queries, joins etc... total p.o.s for those types of functions/methods- just don't use it.
If you logically want to create a collection where you can easily look up a customer by their ID, I would use some form of IDictionary<int, Customer>
. That expresses what you're trying to achieve.
Now you could use a list to do the same thing, and as leppie says for small datasets it will be about as fast or even faster - but for small datasets it'll be very fast anyway, so why do you care? I think it's more important to tell the reader of your code what you're trying to do with the collection - and a dictionary achieves that aim far more effectively than a list, IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With