I decide to make the problem clear from tip to toe.
my test code is from Anders Heilsberg's lecture on Tech-Ed 2004 on C#
Language enhancement. I slightly modified the code,not to the core part but
the display style.
My question is,when I first run the code,the performance of arraylist of
int is best,use only 30-50ms,other three do as expected. When I run the code
again,the arraylist of int has the worst performance,as it should be.I post
my code here,although this board is not convenient to display long code.I
tried my best to cleary layout the code.
Appreciate any help.
using System;
using System.Collections;
using System.Collections.Generic;
delegate void Method();
class Test
{
public string Name;
public Method Code;
public Test(string name,Method code)
{
Name = name;
Code = code;
}
}
class Program
{
static void RunTests(params Test[] tests)
{
for (int index = 0; index < tests.Length; index++) {
tests[index].Code();
}
for (int index = 0; index < tests.Length; index++)
{
DateTime start = DateTime.Now;
for (int i = 0; i < 1000; i++)
tests[index].Code();
TimeSpan time = DateTime.Now - start;
DrawBar(index, time, tests[index].Name);
}
}
static void DrawBar(int index, TimeSpan time, string text)
{
text = " " + text;
Console.WriteLine(text);
ConsoleColor bg = Console.BackgroundColor;
ConsoleColor fg = Console.ForegroundColor;
Console.BackgroundColor = (index & 2) == 0 ? ConsoleColor.DarkBlue :
ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.White;
int size = (int)(time.Milliseconds/10);
if (size > 79) size = 79;
text = " " + time.Milliseconds.ToString() + "ms";
for (int i = 0; i < size; i++)
Console.Write(i < text.Length ? text[i] : ' ');
Console.WriteLine();
for (int i = 0; i < size; i++) Console.Write(' ');
Console.WriteLine();
Console.WriteLine();
Console.BackgroundColor = bg;
Console.ForegroundColor = fg;
}
static void Main(string[] args)
{
Console.WriteLine();
RunTests(
new Test("ArrayList of string",
delegate {
ArrayList list = new ArrayList();
for (int i = 0; i < 10000; i++)
{
list.Add("hello");
string s = (string)list[0];
list.RemoveAt(0);
}
}),
new Test("ArrayList of int",
delegate {
ArrayList list = new ArrayList();
for (int i = 0; i < 10000; i++)
{
list.Add(123);
int x = (int)list[0];
list.RemoveAt(0);
}
}),
new Test("List<string>",
delegate {
List<string> list = new List<string>();
for (int i = 0; i < 10000; i++)
{
list.Add("hello");
string s = list[0];
list.RemoveAt(0);
}
}),
new Test("List<int>",
delegate {
List<int> list = new List<int>();
for (int i = 0; i < 10000; i++)
{
list.Add(123);
int x = list[0];
list.RemoveAt(0);
}
})
);
Console.ReadLine();
}
}