.NET での文字列比較推奨事項
.NET での文字列比較ですが、忘れやすいのでメモしておきます。
- New Recommendations for Using Strings in .NET 2.0
- カルチャを認識しない文字列操作の実行
- Share This : Speed Up String Processing with StringComparison.Ordinal
- DO: Use
StringComparison.Ordinal
orOrdinalIgnoreCase
for comparisons as your safe default for culture-agnostic string matching.- DO: Use
StringComparison.Ordinal
andOrdinalIgnoreCase
comparisons for increased speed.- DO: Use
StringComparison.CurrentCulture
-based string operations when displaying the output to the user.- DO: Switch current use of string operations based on the invariant culture to use the non-linguistic
StringComparison.Ordinal
orStringComparison.OrdinalIgnoreCase
when the comparison is linguistically irrelevant (symbolic, for example).- DO: Use
ToUpperInvariant
rather thanToLowerInvariant
when normalizing strings for comparison.- DON'T: Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.
- DON'T: Use
StringComparison.InvariantCulture
-based string operations in most cases; one of the few exceptions would be persisting linguistically meaningful but culturally-agnostic data.
上記もまとまっていますが、より簡単にまとめます。
日本語や英語など言語 (カルチャ) を考慮しない場合、 String.Compare() に StringComparison.Ordinal か StringComparison.OrdinalIgnoreCase を渡すと、文字列の比較を高速に行うことができます。 String.CompareOrdinal() を使用しても OK です。