Nejc Galof Nejc Galof - 2 months ago 14
C# Question

Finding item in list is slow

I have a list:

List<symbol> table = new List<symbol>();

My class symbol have this structure:

public class symbol
public byte c;
public ulong low;
public ulong high;
public ulong freq;

When I searching in loop right symbol in list, this take too much time:
Just for example:

sim = table.FirstOrDefault(x => x.c == b); //26 sec
sim = table.Where(i => i.c== b).FirstOrDefault(); //20 sec
sim = table.Find(x => x.c == b); //10 sec
sim = table[1]; //3 sec

Here is time from my all program, where I change only this line.
My list size is about 2-256 but I searching about 100mil.
I want searching must quicker then 10 sec in my example.
How can I search more quickly in
? Or exist quick good solution without list with same result?


List is not designed for efficient searching. If speed is important then you need a better data structure.

If you need to find all symbol with byte value c = x then I would have a dictionary of lists of symbols.

var symbols = new Dictionary<byte, List<Symbol>>();

When you add a symbol you should lookup the list and if not found create a new one