Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Net.WebSockets;
- using System.Security.AccessControl;
- using System.Text;
- using NUnit.Framework;
- namespace StructBenchmarking
- {
- public class Benchmark : IBenchmark
- {
- public double MeasureDurationInMs(ITask task, int repetitionCount)
- {
- GC.Collect();
- GC.WaitForPendingFinalizers();
- var watch = new Stopwatch();
- task.Run();
- watch.Start();
- for (var i = 0; i < repetitionCount; i++)
- {
- task.Run();
- }
- watch.Stop();
- return (double)watch.ElapsedMilliseconds / repetitionCount;
- }
- }
- public class ForStringBuilder : ITask
- {
- private int repetitionCount;
- private char letter;
- public ForStringBuilder(int repetitionCount, char letter)
- {
- this.repetitionCount = repetitionCount;
- this.letter = letter;
- }
- string WithStringBuilder()
- {
- var strBuilder = new StringBuilder();
- for (var i = 0; i < repetitionCount; i++)
- strBuilder.Append(letter);
- return strBuilder.ToString();
- }
- public void Run()
- {
- WithStringBuilder();
- }
- }
- public class ForConstructor : ITask
- {
- private int repetitionCount;
- private char letter;
- public ForConstructor(int repetitionCount, char letter)
- {
- this.repetitionCount = repetitionCount;
- this.letter = letter;
- }
- string WithConstructor()
- {
- return new string(letter, repetitionCount);
- }
- public void Run()
- {
- WithConstructor();
- }
- }
- [TestFixture]
- public class RealBenchmarkUsageSample
- {
- [Test]
- public void StringConstructorFasterThanStringBuilder()
- {
- var benchmark = new Benchmark();
- var forConstructor = new ForConstructor(4000000, 'a');
- var forBuilder = new ForStringBuilder(4000000, 'a');
- var builderTime = benchmark.MeasureDurationInMs(forBuilder, 20);
- var constructorTime = benchmark.MeasureDurationInMs(forConstructor, 20);
- Assert.Less(constructorTime, builderTime);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement