General method versus non-general method - is there any performance advantage?

I am creating my first site in C #.

I noticed that I am getting some duplication of extension methods in intellisense. Further research was as follows:

public static void ThrowNullOrEmpty<T>(this IEnumerable<T> obj, string param) { } public static void ThrowNullOrEmpty(this string obj, string param) { } 

It seems the string could also be an IEnumerable<char> .

From the compilation base I can remove the line option, but are there any performance issues or anything else I should know about?

UPDATE

Just tested over 1 m iterations.

 public bool IsNullOrEmpty1(string @this) { return String.IsNullOrEmpty(@this); } 

vs

 public bool IsNullOrEmpty2<T>(IEnumerable<T> @this) { return @this == null || !@this.Any (); } 

IsNullOrEmpty1 synchronized 12 ms on my IsNullOrEmpty2 development machine (125 - 250 ms), so it’s 10-20 times slower.

In the real world, I took an extremely high figure of 30 m iterations per month, which corresponds to 1388 per minute (12-hour work day). The result was less than 1 ms for both.

So, removing IsNullOrEmpty1 is not the best approach, but it is not a site killer.

+4
source share
2 answers

This probably depends on the implementation of these methods - the version of the string can be optimized for performance, and IEnumerable<T> is more general. Calling a generic method has no overhead; it already allowed the correct general parameter at compile time.

The string version can be implemented as follows: it has very little overhead (basically it needs to be done with two comparisons):

 if (String.IsNullOrEmpty(value)) 

IEnumerable<T> , on the other hand, should probably be implemented something like this:

 if (value == null || !value.Any()) 

The key here is calling Any , which will call the GetEnumerator method and return an enumerator. (For simplicity, we will consider performance optimization, which the infrastructure can use internally for some types). This means that the implementation actually creates a new object that will later need to be garbage collected - this will require more clock cycles than the two comparisons mentioned in the string version.

In practice, if these methods are not called very often, I doubt that there is a significant difference in performance.

By the way, the reason for this is because string is an IEnumerable<char> .

+3
source

string is a private class, so we can call methods in the string class directly without accessing the pointer to a virtual function. Theoretically, this is faster than passing I Enumerable<char> . But in practice, it depends on how many times you call the string methods in your method.

0
source

Source: https://habr.com/ru/post/1434450/


All Articles