Introduction
The objective of this article is to elucidate you, fellow developers, to really evaluate the need of using a generic List<T>
instead of an old string[]
, since usually the cost is overlooked.
Using the Code
I've built a simple example to compare the performance for reading and writing to a List<string>
and a string[]
. Concerning the writing time in milliseconds, for 100000 randomly generated items, the string[]
outperformed the List<string>
by approximately 8ms.
const int size = 100000;
Stopwatch startList = new Stopwatch();
startList.Start();
List<string> listString = new List<string>(size);
for (int i = 0; i <= size; i++)
{
string toAdd = Guid.NewGuid().ToString();
listString.Add(toAdd);
}
startList.Stop();
TimeSpan durationList = startList.Elapsed;
Stopwatch startArray = new Stopwatch();
startArray.Start();
string[] arrayString = new string[size];
for (int i = 0; i < size; i++)
{
string toAdd = Guid.NewGuid().ToString();
arrayString[i] = toAdd;
}
startArray.Stop();
TimeSpan durationArray= startArray.Elapsed;
When reading, the string[]
outperforms the List<string>
by approximately 2.5 times faster!!
Stopwatch startListRead = new Stopwatch();
startListRead.Start();
for (int i = 0; i <= listString.Count - 1; i++)
{
string str = listString[i];
}
startListRead.Stop();
TimeSpan durationListRead = startListRead.Elapsed;
Stopwatch startArrayRead = new Stopwatch();
startArrayRead.Start();
for (int i = 0; i <= arrayString.Length - 1; i++)
{
string str = arrayString[i];
}
startArrayRead.Stop();
TimeSpan durationArrayRead = startArrayRead.Elapsed;
And you can still do this with LINQ to Objects with an array, as you do with your List<string>
:
var result = from i in arrayString
where i.StartsWith("a")
select i;
Results:
So, bottom line, you should consider if you really need the List<T>
as opposed to an array because there are serious performance costs that will affect your application.
Points of Interest
Creating concerns on performance of instructions being used in your applications.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.