Created
July 24, 2014 02:52
-
-
Save fotijr/7a97632f4af1c962aeff to your computer and use it in GitHub Desktop.
Console application to test concatenation performance of a string compared with using StringBuilder. Program prompts for string and amount of times to concatenate.
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
using System; | |
using System.Text; | |
using System.Diagnostics; | |
namespace StringBuilderTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var userQuit = false; | |
do | |
{ | |
int concatTimes; | |
Console.Write("Enter string to concatenate: "); | |
string userInput = Console.ReadLine(); | |
Console.Write("Times to concatenate: "); | |
if (!int.TryParse(Console.ReadLine(), out concatTimes) || concatTimes < 0) | |
{ | |
Console.WriteLine("Please enter a number greater than 0!"); | |
Console.WriteLine(); | |
continue; | |
} | |
Console.WriteLine("-----------------------------------------------"); | |
string appended = ""; | |
var swTest = new Stopwatch(); | |
Console.WriteLine("Beginning concatenation test..."); | |
swTest.Start(); | |
for (int i = 0; i < concatTimes; i++) | |
{ | |
appended += userInput; | |
} | |
// Console.WriteLine(appended); | |
swTest.Stop(); | |
Console.WriteLine("Concatenation test finished!"); | |
Console.WriteLine(string.Format("Results in seconds: {0}", swTest.Elapsed.TotalSeconds)); | |
Console.WriteLine(string.Format("Results in ms: {0}", swTest.Elapsed.TotalMilliseconds)); | |
Console.WriteLine(); | |
Console.WriteLine("Beginning StringBuilder test..."); | |
var built = new StringBuilder(); | |
swTest.Restart(); | |
for (int i = 0; i < concatTimes; i++) | |
{ | |
built.Append(userInput); | |
} | |
// Console.WriteLine(built); | |
swTest.Stop(); | |
Console.WriteLine("StringBuilder test finished!"); | |
Console.WriteLine(string.Format("Results in seconds: {0}", swTest.Elapsed.TotalSeconds)); | |
Console.WriteLine(string.Format("Results in ms: {0}", swTest.Elapsed.TotalMilliseconds)); | |
Console.WriteLine("-----------------------------------------------"); | |
Console.WriteLine(); | |
} while (userQuit == false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment