I need to concatenate a lot of strings alltogether and put a comma between any of them. I have a list of strings
\"123123123213\"
\"1232113213213\"
\"1232131
This adhoc implementation I tried with the StrignBuilder is faster than String.Join. More than that String.Join is a MEMORY HOG. I tried with 20000000 strings and String.Join always gives OutOfMemory, when my implementation finishes. On your machine It may be even on less strings if you have less than 8Gb of memory. Comment one of the implementations to test. This holds true unless you use a fixed string[] array. String.Join is good there.
public static void Main(string[] Args)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
List strings = new List() {};
for (double d = 0; d < 8000000; d++) {
strings.Add(d.ToString());
}
TimeSpan upTime;
TimeSpan newupTime;
using (var pc = new PerformanceCounter("System", "System Up Time"))
{
StringBuilder sb = new StringBuilder(strings.Count);
int i;
pc.NextValue(); //The first call returns 0, so call this twice
upTime = TimeSpan.FromSeconds(pc.NextValue());
for (i = 0; i < strings.Count - 1; i++)
{
sb.Append(strings[i]);
sb.Append(",");
}
sb.Append(strings[i]);
newupTime = TimeSpan.FromSeconds(pc.NextValue());
sb = null;
Console.WriteLine("SB " + (newupTime - upTime).TotalMilliseconds);
}
using (var pc = new PerformanceCounter("System", "System Up Time"))
{
pc.NextValue();
upTime = TimeSpan.FromSeconds(pc.NextValue());
string s = string.Join(",", strings);
newupTime = TimeSpan.FromSeconds(pc.NextValue());
Console.WriteLine("JOIN " + (newupTime - upTime).TotalMilliseconds);
}
}
SB 406
JOIN 484