There is a list artList in which ~ 60 artList data. There is also a list of objects of the class List<FileDB> listFileDB = new List<FileDB>(); It is also about ~ 60t data.

 class FileDB { public string Articule { get; set; } public string Naim { get; set; } public string Cnt { get; set; } } 

Question. A lot of CPU time is occupied by the comparison operation. It seems there are no regulars here, and I don’t split. How to speed up the comparison process?

  for (int i = 0; i < artList.Count; i++) { for (int j = 0; j <listFileDB.Count; j++) { if (artList[i] == listFileDB[j].Articule) { // Данная операция очень затратна по ресурсам } } } 
  • 3
    And what exactly do you want to do? You have a double loop, you can certainly save time if you use a more suitable data structure. - VladD

2 answers 2

To be precise, the comparison operation itself takes a lot of time, but enumerates a large number of elements within a loop (nested loops). If your task is to find matching items in two collections and perform some action on them, the following approach may be faster:

 HashSet<string> set1 = new HashSet<string>(artList); HashSet<string> set2 = new HashSet<string>(listFileDb.Select(a => a.Articule)); var res = set1.Intersect(set2); foreach (var item in res) { // Do whatever you want } 

In the List (List), the complexity of accessing an element is linear (it grows in proportion to the size of the list). Considering the processing of two lists in nested loops, the complexity turns out to be quadratic. In the hash set (HashSet) - the time of access to the element is constant. Due to this, a significant gain in speed is obtained. The order of the elements in this case will have to be sacrificed, but in many situations this is uncritical.


Update 1 If you need source elements from listFileDb for further work, try this:

 var selectedItems = listFileDb.Where(item => set1.Contains(item.Articule)); 

set2 in this case does not need to declare. It should turn out much faster than the original example, with nested loops.

  • judging by the question in the artList line, so Select is not needed - Grundy
  • I agree, corrected. - Aleksei
  • one
    and another open question: what exactly the author wants to see in res , if the objects from listFileDb , then the given example does not fit - Grundy
  • I just use two more fields from the listFileDB, so I cannot sample one field - Radzhab
  • Completed the answer. - Aleksei

Generally speaking, you should use alternative data structures. For example, a dictionary ( Dictionary<string,FileDB> ). Or instead of artList, you can use HashSet<string>

But you can get by with lists - if you do Join:

 var pairs = from x in artList join y in listFileDB on x equals y.Articule select y; 

Inside there, by the way, will be all the same dictionary, only temporary.