Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to count number of uppercase characters in c#

Tags:

c#

linq

Any thoughts on the efficiency of this? ...

CommentText.ToCharArray().Where(c => c >= 'A' && c <= 'Z').Count()
like image 471
peterorum Avatar asked Mar 04 '09 08:03

peterorum


1 Answers

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.

like image 50
Matt Hamilton Avatar answered Oct 02 '22 16:10

Matt Hamilton