diff --git a/Testing/Advanced/Advanced.csproj b/Testing/Advanced/Advanced.csproj index d74317f..1a7435e 100644 --- a/Testing/Advanced/Advanced.csproj +++ b/Testing/Advanced/Advanced.csproj @@ -8,6 +8,7 @@ + diff --git a/Testing/Advanced/Samples/4. PerformanceTests/Benchmark.cs b/Testing/Advanced/Samples/4. PerformanceTests/Benchmark.cs new file mode 100644 index 0000000..6fb8f8d --- /dev/null +++ b/Testing/Advanced/Samples/4. PerformanceTests/Benchmark.cs @@ -0,0 +1,83 @@ +namespace Advanced.Samples.Performance; + + +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Running; +using FluentAssertions; +using NUnit.Framework; + +[MemoryDiagnoser(true)] +public class Benchmarks +{ + private const long num = long.MaxValue; + + [Benchmark] + public void GetDigitsFromLeastSignificant_String() + { + num + .ToString() + .Select(x => Convert.ToByte(x.ToString())) + .ToArray(); + } + + [Benchmark] + public void GetDigitsFromLeastSignificant_MathWithSpan() + { + var result = new byte[20]; + var span = new Span(result); + var n = num; + var index = 0; + while (n > 0) + { + span[index] = (byte)(n % 10); + n /= 10; + index++; + } + + var res = span[..index].ToArray(); + } + + [Benchmark] + public void GetDigitsFromLeastSignificant_MathWithList() + { + var result = new List(); + var n = num; + while (n > 0) + { + result.Add((byte)(n % 10)); + n /= 10; + } + } + + [Benchmark] + public void GetDigitsFromLeastSignificant_MathWithYield() + { + IEnumerable Inner() + { + var n = num; + while (n > 0) + { + yield return (byte)(n % 10); + n /= 10; + } + } + + Inner().ToArray(); + } +} + +[TestFixture] +[Explicit] +public class BenchmarkTests +{ + [Test] + public void GetDigitsFromLeastSignificant() + { + var config = ManualConfig + .CreateMinimumViable() + .WithOption(ConfigOptions.DisableOptimizationsValidator, true); + + BenchmarkRunner.Run(config); + } +} \ No newline at end of file