SHARE
TWEET

Untitled

a guest Dec 15th, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Text;
  3. using System.Diagnostics;
  4. using NUnit.Framework;
  5.  
  6. namespace StructBenchmarking
  7. {
  8.     public class Benchmark : IBenchmark
  9.     {
  10.         public double MeasureDurationInMs(ITask task, int repetitionCount)
  11.         {
  12.             GC.Collect();                  
  13.             GC.WaitForPendingFinalizers();
  14.             task.Run();
  15.             var result = 0.0;
  16.             for (var i = 0; i < repetitionCount; i++)
  17.             {
  18.                 Stopwatch stopWatch = new Stopwatch();
  19.                 stopWatch.Start();
  20.                 task.Run();
  21.                 stopWatch.Stop();
  22.                 result += stopWatch.Elapsed.TotalMilliseconds;
  23.             }
  24.             return result / repetitionCount;
  25.         }
  26.     }
  27.     public class StringBuilderMaker : ITask
  28.     {
  29.         public void Run()
  30.         {
  31.             var str = new StringBuilder();
  32.             for (var i = 0; i < 10000; i++)
  33.                 str.Append("a");
  34.         }
  35.     }
  36.     public class StringMaker : ITask
  37.     {
  38.         public void Run()
  39.         {
  40.             var str = new string('a', 10000);
  41.         }
  42.     }
  43.  
  44.     [TestFixture]
  45.     public class RealBenchmarkUsageSample
  46.     {
  47.         [Test]
  48.         public void StringConstructorFasterThanStringBuilder()
  49.         {
  50.             var benchmark = new Benchmark();
  51.             var stringMaker = new StringMaker();
  52.             var stringBuilderMaker = new StringBuilderMaker();
  53.             stringMaker.Run();
  54.             stringBuilderMaker.Run();
  55.             var testCount = 100;
  56.             var stringResult = benchmark.MeasureDurationInMs(stringMaker, testCount);
  57.             var stringBuilderResult = benchmark.MeasureDurationInMs(stringBuilderMaker, testCount);
  58.             Assert.Less(stringBuilderResult, stringResult);
  59.         }
  60.     }
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top