This program concats strings with variety sizes for 1, 10, 100, 1000, 10000, 100000, 1000000 times.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- namespace Test
- {
- class Program
- {
- static string[] data = {"a", "ab", "abc", "abcd", "abcde",
- static void Main(string[] args)
- {
- StringTest();
- //StringBuilderTest();
- //StringMemoryTest();
- //StringBuilderMemoryTest();
- Console.ReadLine();
- }
- static void StringTest()
- {
- string collector = string.Empty;
- int count = 1;
- Console.WriteLine("Loop Time");
- for (int i = 1; i <= 7; i++) //1, 10, 100, 1000, 10000, 100000, 1000000
- {
- sw.Start();
- for (int j = 0; j < count; j++)
- {
- collector = collector + data[j % 10];
- }
- sw.Stop();
- TimeSpan ts = sw.Elapsed;
- Console.WriteLine("{0,-12:d}{1:0} ms", count, ts.TotalMilliseconds);
- count *= 10;
- collector = string.Empty;
- sw.Reset();
- }
- }
- static void StringBuilderTest()
- {
- int count = 1;
- Console.WriteLine("Loop Time");
- for (int i = 1; i <= 7; i++) //1, 10, 100, 1000, 10000, 100000, 1000000
- {
- sw.Start();
- for (int j = 0; j < count; j++)
- {
- collector.Append(data[j % 10]);
- }
- sw.Stop();
- TimeSpan ts = sw.Elapsed;
- Console.WriteLine("{0,-12:d}{1:0} ms", count, ts.TotalMilliseconds);
- count *= 10;
- sw.Reset();
- }
- }
- static void StringMemoryTest()
- {
- string collector = string.Empty;
- int count = 1;
- long m = 0;
- Console.WriteLine("Loop Memory");
- for (int i = 1; i <= 7; i++) //1, 10, 100, 1000, 10000, 100000, 1000000
- {
- for (int j = 0; j < count; j++)
- {
- collector = collector + data[j % 10];
- }
- //m = GC.GetTotalMemory(false);
- m = Process.GetCurrentProcess().PrivateMemorySize64;
- Console.WriteLine("{0,-12:d}{1:0} kb", count, m / 1024);
- count *= 10;
- collector = string.Empty;
- }
- }
- static void StringBuilderMemoryTest()
- {
- int count = 1;
- long m = 0;
- Console.WriteLine("Loop Memory");
- for (int i = 1; i <= 7; i++) //1, 10, 100, 1000, 10000, 100000, 1000000
- {
- for (int j = 0; j < count; j++)
- {
- collector.Append(data[j % 10]);
- }
- //m = GC.GetTotalMemory(false);
- m = Process.GetCurrentProcess().PrivateMemorySize64;
- Console.WriteLine("{0,-12:d}{1:0} kb", count, m / 1024);
- count *= 10;
- }
- }
- }
- }
Here are the results
Execution time with string.
After 10 minutes i terminated the program.
Execution time with stringbuilder
Memory Usage - String
Memory Usage - StringBuilder
Stopwatch@MSDN
GC.GetTotalMemory@MSDN
PrivateMemorySize64@MSDN