Home > Uncategorized > C# 300% #performance increase Dictionaries vs #Linq

C# 300% #performance increase Dictionaries vs #Linq

Simple statment, if you are holding large (1M+) objects in memory, use a Dictionary, don’t use Linq on a Generic List. I saw a 300% improvement using this approach.

So, here is, in pseudocode what I’m talking about.

// SLOW!

List<SomeObject> myList = new List<SomeObject>()

.. Add 1M items to myList

var myObject = myList.FirstOrDefault(o => o.property==id);

Whereas, if you can do this:

// FAST!

Dictionary<int,SomeObject> dList = new Dictionary<int,SomeObject>();

.. Add 1M items to dList

var myObject = dList[id];

It is 300% faster.

My benchmarking code created a 1M item list, and a 1M item dictionary, and ran 100 lookups on each. The Linq approach took 7.6 Seconds, the dictionary took 2 seconds.

Of course, you lose the flexibility of writing filters on other properties, or more complex lookups other than equality.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: