benchmark
StringBuilder vs. Concatenation
1: Intro
After the if vs. ternary deathmatch I started wondering just how much slower string concatenation was versus using a StringBuilder. Below are the test and results, not very surprising though.
2: Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { string[] words = ("Quisque in neque at orci congue " + "tempor. Donec id eros velit, eu " + "sodales est. Sed purus eros, tempor " + "id ultricies eget, volutpat a mauris. " + "Suspendisse potenti. Suspendisse id " + "ligula nec felis mattis pellentesque " + "nec quis ipsum. Vivamus sed metus nunc, " + "non eleifend ligula. Sed mollis sagittis " + "pellentesque. Nam sit amet ante ut risus " + "pulvinar rhoncus. Vestibulum molestie " + "feugiat leo sed placerat. Sed consectetur " + "velit ut magna molestie molestie tincidunt " + "magna viverra. Quisque eu diam lacus. Sed " + "blandit, felis vel sollicitudin pellentesque, " + "sapien nisl ullamcorper mauris, dapibus " + "accumsan diam augue et diam. Ut suscipit " + "nibh pretium nisi pulvinar vitae condimentum " + "felis mattis. Donec justo orci, gravida in " + "aliquam et, cursus sit amet sapien. Pellentesque " + "mauris ipsum, ornare ac blandit nec, pretium " + "nec purus. Curabitur malesuada, lectus at " + "fermentum tempus, risus orci condimentum " + "lorem, id consequat dolor velit sed arcu. " + "Duis hendrerit rutrum tellus, a dignissim " + "velit facilisis ac. Curabitur pretium quam a " + "metus sagittis mattis. Cum sociis natoque " + "penatibus et magnis dis parturient montes, " + "nascetur ridiculus mus.").Split(" ".ToCharArray()); TimeSpan concatenationTestTime = TestConcatenation(words); TimeSpan stringbuilderTestTime = TestStringBuilder(words); Console.WriteLine(string.Format("StringBuilder: {0}", stringbuilderTestTime)); Console.WriteLine(string.Format("Concatenation: {0}", concatenationTestTime)); Console.ReadLine(); } static TimeSpan TestConcatenation(string[] words) { string finalResult = string.Empty; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 100; i++) { foreach (string word in words) { finalResult = finalResult + word; finalResult = finalResult + " "; } } sw.Stop(); return sw.Elapsed; } static TimeSpan TestStringBuilder(string[] words) { string finalResult = string.Empty; StringBuilder full = new StringBuilder(); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 100; i++) { foreach (string word in words) { full.Append(word); full.Append(" "); } } finalResult = full.ToString(); sw.Stop(); return sw.Elapsed; } } } |
3: Results
The not too surprising results: StringBuilder is a lot faster than string concatenation.
If vs Ternary: Deathmatch
1: INTRO
The Fun With the ?? Operator in C#: if { } or ?? – Which is Faster? article by Keith Elder got me thinking about the if statement and the ternary operator.
Is there a real difference or are they both the same?
To answer this question I put together a little project that tests both cases and times them.
2: CODE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | using System; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string[] strArray = new string[20000]; Random r = new Random((int)DateTime.Now.Ticks); for (int i = 0; i < 500; i++) { int rnum = r.Next(); if (rnum % 2 == 0) { strArray[i] = null; } else { strArray[i] = rnum.ToString(); } } TimeSpan ts1 = TimeSpan.Zero; TimeSpan ts2 = TimeSpan.Zero; for (int i = 0; i < strArray.Length; i++) { ts2 = ts2.Add(countWithTernary(strArray)); ts1 = ts1.Add(countWithIf(strArray)); } for (int i = 0; i < strArray.Length; i++) { ts1 = ts1.Add(countWithIf(strArray)); ts2 = ts2.Add(countWithTernary(strArray)); } Console.WriteLine(" if: " + ts1.TotalMilliseconds.ToString()); Console.WriteLine("ternary: " + ts2.TotalMilliseconds.ToString()); Console.ReadLine(); } private static TimeSpan countWithIf(string[] arr) { Stopwatch sw = new Stopwatch(); int len = arr.Length; int count = 0; sw.Start(); for (int i = 0; i < len; i++) { if (arr[i] == null) { count += 1; } else { count += 2; } } sw.Stop(); return sw.Elapsed; } private static TimeSpan countWithTernary(string[] arr) { Stopwatch sw = new Stopwatch(); int len = arr.Length; int count = 0; sw.Start(); for (int i = 0; i < len; i++) { count += arr[i] == null ? 1 : 2; } sw.Stop(); return sw.Elapsed; } } } |
3: RESULTS
The output of the above code suprised me, here are the results:
Here we see that using the if statement is much faster than the ternary operator.
In release the if statement gets faster and the ternary stays about the same.
Surprising to me here was when compiled with x64 the if statement was just as slow (or even slower) than the ternary one.
In release for the x64 they're both almost the same again but the ternary operation is faster than the x86 version.
4: CONCLUSION
In conclusion i think using the if statement would be faster in most cases although in most applications the difference would be unnoticeable.