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" };
-
-
- GenericList.Sort();
- stopwatchGenericList.Stop();
- Console.WriteLine($"Generic Sort" + Environment.NewLine +
- $"{nameof(GenericList)} : {GenericList}" + Environment.NewLine +
- $"Time taken: {stopwatchGenericList.Elapsed.TotalMilliseconds} ms" + Environment.NewLine);
-
-
- 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