Performance Quiz #7 -- Generics Improvements and Costs
Time for another quiz for you all, this is just a micro-benchmark so we want to be careful not to conclude too much but it's useful for understanding the costs and their origins. Consider the two snippets shown below:
// choice #1, using Generics
int total = 0;
List<int> li = new List<int>();
for (i = 0; i < 20; i++)
li.Add(i);
// start timer
for (i = 0; i < 10000000; i++)
foreach (int el in li)
total += el;
// end timer
// choice #2, using ArrayList
ArrayList al = new ArrayList();
for (i = 0; i < 20; i++)
al.Add(i);
// start timer
for (i = 0; i < 10000000; i++)
foreach (int el in al)
total += el;
// end timer
Now try to answer these question (no peeking at the comments until you've done your work :))
Q1: Which is faster?
Q2: How much faster?
Q3: Why is it faster?
Q4: What price do we pay for this speed? Quantify it if you can.
Answers and discussion soon :)