I am creating my first website in C#.
I noticed I was getting some duplication of extension methods in intellisense. Onfurther investigation it was these two:
public static void ThrowNullOrEmpty<T>(this IEnumerable<T> obj, string param)
{
}
public static void ThrowNullOrEmpty(this string obj, string param)
{
}
It seems string can also be IEnumerable<char>.
From a basis of compiling I can remove the string variant, but are there any performance issues or anything else I should be aware of?
UPDATE
Just tested over 1m iterations.
public bool IsNullOrEmpty1(string @this)
{
return String.IsNullOrEmpty(@this);
}
vs
public bool IsNullOrEmpty2<T>(IEnumerable<T> @this)
{
return @this == null || !@this.Any();
}
IsNullOrEmpty1 clocked 12 ms on my development machine, IsNullOrEmpty2 (125 – 250ms), so 10 – 20 times slower.
In the real world, I took an extremely high figure of 30m iterations per month, which translates back to 1388 per minute (12 hour day). The result was less than 1ms for both.
So, removing IsNullOrEmpty1 is not the best approach but its not a site killer either.
It probably depends on the implementation of those methods – the string version could be optimized for performance, while the
IEnumerable<T>one needs to be more general. Calling a generic method has no overhead, it is already resolved to the correct generic parameter at compile time.The string version can be implemented like this, which has very little overhead (it basically needs to make two comparisons):
The
IEnumerable<T>on the other hand probably has to be implemented something like:The key here is the
Anycall which will invoke the GetEnumerator method and return an enumerator. (For simplicity, we will overlook the performance optimizations that the framework might use internally for some types, here). This means that the implementation actually creates a new object, which will later need to be garbage collected – both will require more clock cycles than making the two comparisons mentioned in thestringversion.In practice, unless these methods are called very frequently, I doubt there is any significant performance difference.
Btw, the reason why this works, is that
stringis anIEnumerable<char>.