Created
July 26, 2017 19:52
-
-
Save philipmat/aac59dba64ce0fa7398b001d9b459e32 to your computer and use it in GitHub Desktop.
Speed of String Concatenation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: