We can use a string List instead of a string Array. But this has a performance cost. Consider this benchmark—we loop over a string List, and loop over a string Array.
using System;
using System.Collections.Generic;
using System.Diagnostics;
List<string> colorsList = new List<string>();
colorsList.Add(
"blue");
colorsList.Add(
"red");
colorsList.Add(
"orange");
colorsList.Add(
"aqua");
string[] colorsArray = new string[4];
colorsArray[0] =
"blue";
colorsArray[1] =
"red";
colorsArray[2] =
"orange";
colorsArray[3] =
"aqua";
const int _max = 2000000;
int sum = 0;
var s1 = Stopwatch.StartNew();
// Version 1: use string List.
for (int i = 0; i < _max; i++)
{
foreach (string item in colorsList)
{
sum += item.Length;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use string array.
for (int i = 0; i < _max; i++)
{
foreach (string item in colorsArray)
{
sum += item.Length;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
32.93 ns foreach string List
4.61 ns foreach string[]