String
List
In C# we sometimes need to store strings. We might want to store some of them in a collection, packed together—in a string
List
.
With a string
List
, each element is added with a method like Add. The strings are stored separately, with references pointing to each one, in the List
.
Consider this example program. We create a string
List
and add 3 values to it—these are stored in the order added.
for
-loop over the string
List
. See carefully how the index is used to access each item in the values List
.foreach
-loop passes over all elements, and no index int
is used. We test each string
with char.IsUpper
.using System; using System.Collections.Generic; List<string> values = new List<string>(); values.Add("one"); values.Add("two"); values.Add("THREE"); // Use for loop. for (int i = 0; i < values.Count; i++) { // Get element at this index. string value = values[i]; // Display with string interpolation. Console.WriteLine($"Value {i}: {value}"); } // Use foreach loop. foreach (string value in values) { if (char.IsUpper(value[0])) { Console.WriteLine($"Uppercase: {value}"); } }Value 0: one Value 1: two Value 2: THREE Uppercase: THREE
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.
foreach
-loop is done of the string
List
. Accesses each string
in the list.foreach
-loop acts on the string
Array. It gets the length for each string
(the same as Version 1).string
Array is faster for the foreach
-loop. Even if the tests are reordered, the result seems to be consistent.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[]
String
array noteWe cannot add items to an array as easily—we must manage the size ourselves. For a string
list, we can just call Add()
as much as needed. This makes programs simpler.
Changing a string
List
to a string
array may have performance benefits in programs. A simple foreach
-loop may perform better. In most programs, a string
List
is a good choice.