Optimizing my Search function using foreach() - perfomance

126 Views Asked by At

Here is the deal. I have got 3 Tables.

  1. Main ( contains ID and a list of SubMain ) ~ 130 items (after first filtering)

  2. SubMain (contains SubMainID) ~ 120 items (which got a n to m reference so there is an other table)

  3. MainToSub ( contains ID, MainID and SubMainID) ~ 500 items

Main is my Model which im working with and which I display in the GridView. With this foreach I search for every Model part which has SearchSubMainID in it. This works but the problem is that i am jumping more then 72000 into the foreach which isn't really optimized

foreach (var item in MainToSub)
{ 
 // 500 Jumps
    foreach (var temp in Main)
    {
        if (item.MainID == temp.ID && item.SubMainID == SearchSubMainID)
        {
            Model.Add(temp);
            // ~ 10 Jumps
        }
       // 72000 jumps
    }
}

Question: Is there a way to optimize the foreach?

3

There are 3 best solutions below

0
On BEST ANSWER

Well, you could move one of the checks up one foreach:

foreach (var item in MainToSub)
    if (item.SubMainID == SearchSubMainID)
        foreach (var temp in Main)
            if (item.MainID == temp.ID)
                Model.Add(temp);

And this isn't really optimization, but you could also turn it into a LINQ expression:

foreach (var temp in MainToSub
    .Where(i => i.SubMainID == SearchSubMainID)
    .Join(Main, i => i.MainID, t => t.ID, (i, t) => t))
        Model.Add(temp);
0
On

You could use a Dictionary, make you own class to be used as a key containing the MainID and the SubMainID. With this Dictionary you don't have to search, you just find ... kind of.

0
On

You can also sort your lists and try to search it using BinarySearch - you have then O(log n). But solution with Dictionary is much simpler.