A short note for Generics
Type safety & Performance
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. // Sorting generic list
  8. GenericList.Sort();
  9. stopwatchGenericList.Stop();
  10. Console.WriteLine($"Generic Sort" + Environment.NewLine +
  11. $"{nameof(GenericList)} : {GenericList}" + Environment.NewLine +
  12. $"Time taken: {stopwatchGenericList.Elapsed.TotalMilliseconds} ms" + Environment.NewLine);
  13. // Sorting non generic list
  14. NonGenericArrayList.Sort();
  15. stopwatchNonGenericList.Stop();
  16. Console.WriteLine($"Non-Generic Sort" + Environment.NewLine +
  17. $"{nameof(NonGenericArrayList)} : {NonGenericArrayList} " + Environment.NewLine +
  18. $"Time taken: {stopwatchNonGenericList.Elapsed.TotalMilliseconds} ms");
  19. }
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