Generics: Performance & type safety with example

A short note for Generics
  • According to msdn “Generics are essentially a ‘code template’ that allows developers to define type-safe data structures without committing to an actual data type”.
  • Introduced in .net framework 2.0
Type safety & Performance
  • Generics are type safe because generics are available at run time, It means the runtime knows what type of data structure you're using and can store it in memory more efficiently.
In generics, developer can write code without incurring the cost or risk of runtime cast (boxing & unboxing) operations, so the code execution time decreases
 
Source Code
  1. public static void GenericListPerformanceTest()      
  2. {      
  3.     var stopwatchGenericList = Stopwatch.StartNew();      
  4.     var stopwatchNonGenericList = Stopwatch.StartNew();  
  5.     var GenericList = new List<int> { 12, 89, 102, 34, 84, 67, 21 };      
  6.     var NonGenericArrayList = new ArrayList { 12, 89, 102, 34, 84, 67, 21, "Test string" };      
  7.       
  8.     // Sorting generic list       
  9.     GenericList.Sort();      
  10.     stopwatchGenericList.Stop();      
  11.     Console.WriteLine($"Generic Sort" + Environment.NewLine +      
  12.         $"{nameof(GenericList)} : {GenericList}" + Environment.NewLine +      
  13.         $"Time taken: {stopwatchGenericList.Elapsed.TotalMilliseconds} ms" + Environment.NewLine);      
  14.       
  15.     // Sorting non generic list       
  16.     NonGenericArrayList.Sort();      
  17.     stopwatchNonGenericList.Stop();      
  18.     Console.WriteLine($"Non-Generic Sort" + Environment.NewLine +      
  19.         $"{nameof(NonGenericArrayList)} : {NonGenericArrayList} " + Environment.NewLine +      
  20.         $"Time taken: {stopwatchNonGenericList.Elapsed.TotalMilliseconds} ms");      
  21. } 
1. Performance test
 
 
Output
 
 
2. Type safety test
 
Let’s update the above code, Add a new string in GenericList, we can see a compile time error occurs for invalid type.

 
 
 
Let’s modify the same in NonGenericArrayList, we can see
  1. No compile time error because arraylist store data in object type
  2. But in runtime while performing the sort operation we got InvalidOperationException 
 
 
 
Next Recommended Reading Generics In C# With Example