Created
January 5, 2021 10:54
-
-
Save badamczewski/18590f84f404134a594fe864739a71b7 to your computer and use it in GitHub Desktop.
Switch-Case_Optimization.cs
This file contains hidden or 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 PowerUp.Core; | |
| using PowerUp.Core.Console; | |
| using System; | |
| using System.Numerics; | |
| using System.Runtime.CompilerServices; | |
| using System.Threading; | |
| using BenchmarkDotNet; | |
| using BenchmarkDotNet.Attributes; | |
| using BenchmarkDotNet.Running; | |
| using BenchmarkDotNet.Order; | |
| using System.Collections.Generic; | |
| [Orderer(SummaryOrderPolicy.SlowestToFastest, MethodOrderPolicy.Declared)] | |
| public class SwitchBench | |
| { | |
| private int[] data = new int[64]; | |
| [GlobalSetup] | |
| public void Data() | |
| { | |
| Random rnd = new Random(); | |
| for (int i = 0; i < data.Length; i++) | |
| data[i] = rnd.Next(0, 4); | |
| } | |
| [Benchmark(Baseline = true)] | |
| //[ArgumentsSource(nameof(Numbers))] | |
| public int MultiSwitchUniform() | |
| { | |
| int s = 0; | |
| foreach (var n in data) | |
| s+=MultiSwitch(n, n); | |
| return s; | |
| } | |
| public int MultiSwitch(int x, int y) | |
| { | |
| switch (x, y) | |
| { | |
| case (1, 1): return 1; | |
| case (2, 2): return 2; | |
| case (3, 3): return 3; | |
| } | |
| return 0; | |
| } | |
| [Benchmark] | |
| //[ArgumentsSource(nameof(Numbers))] | |
| public int MultiSwitchCustomUniform() | |
| { | |
| int s = 0; | |
| foreach (var n in data) | |
| s+=MultiSwitchCustom(n, n); | |
| return s; | |
| } | |
| public int MultiSwitchCustom(int x, int y) | |
| { | |
| switch (x) | |
| { | |
| case 1: | |
| { | |
| if (y != 1) break; | |
| return 1; | |
| } | |
| case 2: | |
| { | |
| if (y != 2) break; | |
| return 2; | |
| } | |
| case 3: | |
| { | |
| if (y != 3) break; | |
| return 3; | |
| } | |
| } | |
| return 0; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment