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
- public static void GenericListPerformanceTest()
- {
- var stopwatchGenericList = Stopwatch.StartNew();
- var stopwatchNonGenericList = Stopwatch.StartNew();
- var GenericList = new List<int> { 12, 89, 102, 34, 84, 67, 21 };
- var NonGenericArrayList = new ArrayList { 12, 89, 102, 34, 84, 67, 21, "Test string" };
- // Sorting generic list
- GenericList.Sort();
- stopwatchGenericList.Stop();
- Console.WriteLine($"Generic Sort" + Environment.NewLine +
- $"{nameof(GenericList)} : {GenericList}" + Environment.NewLine +
- $"Time taken: {stopwatchGenericList.Elapsed.TotalMilliseconds} ms" + Environment.NewLine);
- // Sorting non generic list
- NonGenericArrayList.Sort();
- stopwatchNonGenericList.Stop();
- Console.WriteLine($"Non-Generic Sort" + Environment.NewLine +
- $"{nameof(NonGenericArrayList)} : {NonGenericArrayList} " + Environment.NewLine +
- $"Time taken: {stopwatchNonGenericList.Elapsed.TotalMilliseconds} ms");
- }
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
- No compile time error because arraylist store data in object type
- But in runtime while performing the sort operation we got InvalidOperationException

Ishoo AnyalPosted Sep 27, 2019, 5:41 AM
Your comparison for performance is very good. But you forgot one thing. When the code runs for first time, JIT does some compilation which takes extra time, So your time comparison is not the actual running time. For better performance result you should consider using a for loop to call the same method then see the time taken by sorting. Result may not change but time values may surprise you.