Search code examples
c#linq

Fastest way to count number of uppercase characters in C#


What is the efficiency of this? ...

CommentText.ToCharArray().Where(c => c >= 'A' && c <= 'Z').Count()

Solution

  • Ok, just knocked up some code to time your method against this:

    int count = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (char.IsUpper(s[i])) count++;
    }
    

    The result:

    Yours: 19737 ticks

    Mine: 118 ticks

    Pretty big difference! Sometimes the most straight-forward way is the most efficient.

    Edit

    Just out of interest, this:

    int count = s.Count(c => char.IsUpper(c));
    

    Comes in at at around 2500 ticks. So for a "Linqy" one-liner it's pretty quick.