If you haven’t gone through my previous article on generics then please go through it here.

In my previous article, we discussed about the type safety and code re-usability feature of generics, continuing on that, in this article we will discuss about the performance improvement generics brings in to our code.

How usage of generics improves performance ?

Generics can bring performance improvement in terms of speed and memory consumption as follows.

  • With generics in our program, we don’t need to use type casting, that eliminates the extra work compiler does to check the type at run-time. This certainly improves the performance of the application.
  • Another benefits generics bring is that, it eliminates the possibility of boxing and un-boxing in most of the situations, which generally improves the performance and reduces the memory consumption.

Lets take an example of non generic type :

In below example, we are using a non generic type ArrayList to hold some object variables and then evaluating the time spent to read the data from the ArrayList.

Generics in C# performance check
Figure – 1 – Generics in C# performance check

Output :

When the above code executes, then the compiler takes around 3.1544 millisecond to read the data from the non generic ArrayList and append in to the string builder object.

Lets take an example of generic type :

In below example, we are using a generic type List<string> to hold a string variable and evaluating the time spent to read the data from the List<string>.

Output:

When above code executes, then the compiler takes around 0.9073 millisecond to read the data from the generic List<string> and appends in to the string builder object.

If you look at both output, then generic type is the clear winner. It takes less time to execute comparatively to non generic type. So the question arises, Why the compiler took more time while dealing non generic types ?

  • If you look at the non-generic example closely then here what happens. In the code nonGenArrayList.Add(Guid.NewGuid()); , the compiler perform a casting operation to convert Guid.NewGuid(); to object.
  • Again, when it hit the line foreach (string gui in list) , then compiler performs a casting operation to convert from object to string. This extra work that compiler performs makes it slower.
  • However, in the generic example, there is no overhead of type casting during run time, since there is already compile time type check has performed, thus makes it faster.

I hope this article gave you some idea about the basics of generics and its usage. We will deep dive more in to generics in upcoming days, keep visiting to the site and also drop your invaluable feedback’s.