开发者

C# Nested foreach loop optimization

开发者 https://www.devze.com 2023-04-12 19:39 出处:网络
I\'ve got a nested foreach loop that I really need to cut the computation time on. Each collection is at about 50 members, so the extrapolation is huge. I\'ve looked at a lot of information 开发者_如何

I've got a nested foreach loop that I really need to cut the computation time on. Each collection is at about 50 members, so the extrapolation is huge. I've looked at a lot of information 开发者_如何转开发about SelectMany, but I'm still not entirely sure how to use it, or if it's the correct solution.

List<string> StringList; //Populated in previous code
Type[] assemblyTypes = RandomAssembly.GetTypes();

foreach (String name in StringList)
{                               
  foreach (Type at in assemblyTypes)
  {                             
    if (name == at.Name)
    {                                       
      //Do stuff.
    }
  }
}

Thanks in advance!


Use a lookup (such as a dictionary) to increase the speed of checking for a type name:

List<string> StringList; //Populated in previous code
Dictionary<string,Type> assemblyTypes = RandomAssembly.GetTypes()
    .ToDictionary(t => t.Name, t => t);

foreach (String name in StringList)
{                               
    if (assemblyTypes.ContainsKey(name))
    {                                       
      //Do stuff.
    }
  }
}

You should also check which of the 2 collections (StringList or assemblyTypes) is likely to be larger. You generally want the larger one to be converted to the lookup in order to reduce the number of iterations.


Load Type[] into a Dictionary or HashSet (depending on your version of .NET) and then the inner loop disappears.

List<string> StringList; //Populated in previous code
Type[] assemblyTypes = RandomAssembly.GetTypes();
Dictionary<String,Type> typesHash = new Dictionary<String,Type>();
foreach ( Type type in assemblyTypes ) {
  typesHash.Add( type.Name, type );
}

foreach (String name in StringList) {                               
  Type type = null;
  if ( typesHash.TryGetValue( name, out type ) ) {
    // do something with type
  }
}


You might try something like:

assemblyTypes.Where(x => StringList.Contains(x.Name));

Keep in mind this is case sensitive and ignores whitespace, so you will need to add case consideration or trimming if that's an issue.

Edit: (example for loop usage)

foreach (Type item in assemblyTypes.Where(x => StringList.Contains(x.Name)))
{
    // Do stuff
}


If your array/list contains lots of items , you can try using Parallel ForEach loop.


The best optimization might be by querying not for the name but instead for an implemented interface.

Make sure you are optimizing the correct issue/part of your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消