Skip to content

Instantly share code, notes, and snippets.

@philipmat
Created July 26, 2017 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipmat/aac59dba64ce0fa7398b001d9b459e32 to your computer and use it in GitHub Desktop.
Save philipmat/aac59dba64ce0fa7398b001d9b459e32 to your computer and use it in GitHub Desktop.
Speed of String Concatenation
var s1 = string.Empty;
var s2 = new List<string>();
var s3 = new System.Text.StringBuilder();
var sw = new Stopwatch();
const string Message = "Hello I am string number {0}";
sw.Restart();
for (int i = 0; i < 30; i++) {
s1 += string.Format(Message, i) + "\n";
}
sw.Stop();
s1.Dump($"String concat in: {sw.ElapsedTicks}ms");
sw.Restart();
for (int i = 0; i < 30; i++) {
s2.Add(string.Format(Message, i));
}
s1 = string.Join("\n", s2);
sw.Stop();
s1.Dump($"List in: {sw.ElapsedTicks}ms");
sw.Restart();
for (int i = 0; i < 30; i++) {
s3.AppendLine(string.Format(Message, i));
}
s1 = s3.ToString();
sw.Stop();
s1.Dump($"StringBuilder in: {sw.ElapsedTicks}ms");
@philipmat
Copy link
Author

Results:

  • String concat in: 152ms
  • List in: 95ms
  • StringBuilder in: 44ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment