With inspiration from the previous replies (and using both Parallel and unsafe)
Spoiler
static unsafe int CountCharactersOptimized(string str, char c)
{
int partitions = 100;
int partitionSize = str.Length / partitions;
int total = 0;
fixed (char* psz = str)
{
char* start = psz;
Parallel.For<int>(0, partitions, () => 0, (i, loop, subtotal) =>
{
char* low = start + i * partitionSize;
int len = partitionSize / 2;
while (len-- > 0)
{
if (*low++ == c) subtotal++;
if (*low++ == c) subtotal++;
}
return subtotal;
}, (x) => Interlocked.Add(ref total, x));
}
return total;
}

New Topic/Question
Reply



MultiQuote


|