Reputation: 7013
I want to have around 20,000 complex objects sitting in memory at all times (app will run in indefinite loop). I am considering using either List<MyObject>
and then converting the list to Dictionary<int, MyObject>
or just avoiding List alltogether and keeping the objects in dictionary. I was wondering, is it pricey to convert list to dictionary each time i need to look up an object? What would be better? Have them stored as Dictionary at all times? Or have List and using lambdas to get the needed object? Or should i look at other options?
Please note, I don't need queue or stack behavior when object retrieval causes dequeuing.
Thanks in advance.
Upvotes: 0
Views: 326
Reputation: 22332
Regardless of what you're doing, if you need to access the List
, then you are going to need to loop through it to find whatever you want.
If you need to access the Dictionary
, then you have the option to use the key value to immediately retrieve what you are looking for, or, if you must, you can still loop through the Dictionary
's Values
.
Just use the Dictionary
.
Upvotes: 2
Reputation: 144112
Using a lambda lookup against the list is O(N), which for 20,000 items is not inconsiderable. However, if you know you'll always need to fetch the object by a known key, you can use a dictionary which is O(1) - that's as fast as algorithms go. So if there's some way you can structure your data/application so that you can base retrieval around some sort of predictable, repeatable, unique key, that will maximize performance. The worst thing (from a performance standpoint) is some complex lookup routine against a list, but sometimes it is unavoidable.
Upvotes: 2