Improve performance in iteration

Asked

Viewed 101 times

3

I have a C# method that receives a List<string> and I must return a string with the list of members of the List<string> ordered by number of occurrences and then alphabetically.

I did and it already worked, but not with the expected performance.

public string getMostOccuredString(IList<string> lista)
{
     var mostOccured = lista
                         .GroupBy(a => a)
                         .Select(g => new { g.Key, Count = g.Count() })
                         .OrderByDescending(c => c.Count)
                         .ThenBy(c => c.Key);

     string retorno = "";

     foreach (var item in mostOccured)
     {
          retorno = retorno + ";" + item.Key;
     }

     return retorno;
}
  • 1

    Using "for" instead of "foreach" and Stringbuilder instead of concatenation can help improve performance.

  • although it is a minimal difference in performance you could exchange this foreach for a string.Join that is relatively more elegant and slightly more performative, example:return = String.Join(";", mostOccured);

  • 1

    @Lucasmiranda the difference will be brutal, just does not do the same as this tie. It may even be that he wanted more the Join()that tie, but we have no way of knowing.

  • ah yes, I didn’t see there that he was catching the key, well observed

1 answer

6


If the desire is performance forget the LINQ, it is not fast, it lets write more expressively, or cute or short as some will say, but it is not fast. It’s not tragic, but it’s not for speed, take it out and do it in your hand. Take a look at documentation.

Sure, test, there are cases that may not be quite so, even because it can do manually and get worse than it should.

But what’s worse in this code is the problem of strings no need. This fills the memory and puts pressure on the garbage collector causing the system to go into pauses. This is explained in Why should I use the Stringbuilder class instead of the String class?. Also Which the fastest in the construction of text?. An example.

Who knows can use the Join() instead of the loop, the execution will not give the same result, but it may be even better for what you want.

Another issue is to see if you can’t receive an already sorted list or use a data structure that automatically classifies the data. I don’t know if you can do that, but it’s something to think about. Often the question of performance cannot be solved punctually, need to think the whole. Or accept that speed is bad, not everything can be improved if you can’t touch other points. Just note the previous items that will make a difference, especially the StringBuilder.

  • Show @Maniero . Thanks for the tips. Really the string question is very valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.