I've been using StringComparer.CurrentCultureIgnoreCase
for case-insensitive comparisons and hashing. But after checking the Reference Source I see it creates a new instance with every call (shouldn't it be a static function then? Just for form's sake). Anyway my question is, when you have multiple comparisons to do, like an IEquality<T>
implementation, is it efficient to do:
// 2 instances per call
return StringComparer.CurrentCultureIgnoreCase.Equals(this.a, other.a)
&& StringComparer.CurrentCultureIgnoreCase.Equals(this.b, other.b) .. etc ..
Or maybe:
public bool Equals(MyObj other)
{
// 1 instance per call
var equ = StringComparer.CurrentCultureIgnoreCase;
return equ.Equals(this.a, other.a)
&& equ.Equals(this.b, other.b) .. etc ..
}
Or even cache/pool the comparers so they arn't created every time Equals()
is called?
// 1 instance per thread
[ThreadStatic]
private static StringComparer equ;
public bool Equals(MyObj other)
{
if (equ == null) equ = StringComparer.CurrentCultureIgnoreCase;
return equ.Equals(this.a, other.a)
&& equ.Equals(this.b, other.b) .. etc ..
}
Any feelings on which is best practice?
(Thanks to michael-liu for pointing out by original reference to OrdinalIgnoreCase is not a new instance, I've switched to CurrentCultureIgnoreCase which is)