Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster string comparison in C#

I have a program that compares two files. I ran visual studio analysis and found that my comparison time is large. Is there a quicker way to compare two string than this? (I can't use parallel foreach because it might causes errors.) Right now I'm using a concurrent dictionary but I'm open to other options. :)

var metapath = new ConcurrentDictionary<string, string>();
foreach(var me in metapath)
{
 if (line.StartsWith(me.Key.ToString()))
 {...}
}

2 Answers

First of all, drop the ToString() from me.Key.ToString().

Next, use the ordinal string comparison (provided that this doesn’t impact correctness):

line.StartsWith(me.Key, StringComparison.Ordinal);

This is beneficial because standard string comparisons follow various Unicode rules on what’s equal. For example, normalized and denormalized sequences must be treated as equal. Ordinal just compares raw character data, ignoring Unicode equality rules. There is more detail on this here, for example, or here (which claims it’s faster but without quoting any numbers).

Last, profile the code. You’ll be surprised, but most of the time the slow part is not at all what you think it is. For example, it could be the part where you add things to the dictionary.

like image 68
Roman Starkov Avatar answered May 26 '26 18:05

Roman Starkov


If you compare strings exactly, String.Equals is quite good:

String.Equals(line, me.Key)

Have you seen this: What is the fastest (built-in) comparison for string-types in C#

like image 40
AFD Avatar answered May 26 '26 19:05

AFD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!