I was reading through a Microsoft certfication training kit book, when I came upon a discussion about the performance of data structures which use generics, against those that use objects (and boxing). Intrigued, I knocked up a couple of Linked List types for a test.
The implementations of the Linked Lists were identical, bar the fact that one used Generics, whilst the other used Objects. I then used 2 successive, long-running for loops, each performing inserts on the respective Linked Lists, to test the performance of each. The System.Diagnostics.Stopwatch()
class came in very handy:
static void Main(string[] args) { ObjectNS.LinkedList objectsList = new ObjectNS.LinkedList(); GenericNS.LinkedList<int> genericLinkedList = new GenericNS.LinkedList<int>(); // first, time the performance of genericLinkedList inserts System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); for (int i = 0; i < 300000; i++) genericLinkedList.Insert(i, genericLinkedList.Count); watch.Stop(); Console.WriteLine("Performance of Generics - {0}", watch.Elapsed.ToString()); // second, time the performance of objectsList inserts watch.Reset(); watch.Start(); for (int i = 0; i < 300000; i++) objectsList.Insert(i, objectsList.Count); watch.Stop(); Console.WriteLine("\nPerformance of Object/Casting - {0}", watch.Elapsed.ToString()); Console.WriteLine("\n\nPress any key to close window"); Console.Read(); }
And the result:
- Generics vs Objects – Performance Comparison
So, it looks like the performance penalty of boxing the integers was enough to give generics a clear victory. And of this, I am glad. Generics are very cool and easy to use. So, finding out that they also perform well – that’s icing on the cake.
You can download the whole code for my test here.