Search code examples
c#linqcollectionscomplexity-theoryoftype

List.OfType() speed, alternative data structures


Take a look at this code.

interface ILoader
{
}

interface ILoader<T>: ILoader
{
    T Load();
}

class CarLoader: ILoader<Car>
{
    ...
}

class TrainLoader: ILoader<Train>
{
    ...
}

class Container
{
     List<ILoader> loaders = new ILoader[] { new CarLoader(), new TrainLoader()};

     public T Load<T>()
     {
         // Finding right loader
         var loader = loaders.OfType<ILoader<Car>>.FirstOrDefault();
         return loader.Load();
     }
}

I've got about 100 of loaders and I need to load a lot of Trains, Cars, etc. I think that List of loaders is very slow (has OfType() linear complexity??), what do you suggest to use instead of list? Dictionary<Type,ILoader> or Hashtable<Type,ILoader> or HashSet<ILoader>? How fast would be for example to use hashset.OfType<ILoader<Car>>(), same as list or faster?


Solution

  • Build a Dictionary<Type, ILoader> and populate it with the loaders. Then you can just do:

    ILoader<T> loader = (ILoader<T>) loaderDictionary[typeof(T)];
    

    On the other hand, if you've only got 100 items to look through, even a linear scan isn't exactly going to take long. Have you actually benchmarked a real usage situation and found this to be your bottleneck?