├── .gitignore ├── LICENSE ├── README.md └── src └── Practical.BenchmarkDotNet ├── Practical.BenchmarkDotNet.sln └── Practical.BenchmarkDotNet ├── ArrayBoundsCheckBenchmarks.cs ├── ArrayCopyBenchmarks.cs ├── ArrayFirstLastBenchmarks.cs ├── ArrayLoopBenchmarks.cs ├── ArraySizeBenchmarks.cs ├── CheckAlphanumericBenchmarks.cs ├── DictionaryBenchmarks.cs ├── DictionaryLookupVsPatternMatchingBenchmarks.cs ├── DictionaryLoopBenchmarks.cs ├── FrozenDictionaryBenchmarks.cs ├── HashBenchmarks.cs ├── JsonDeserializeBenchmarks.cs ├── JsonSerializerOptionsBenchmarks.cs ├── ListCopyBenchmarks.cs ├── ListFirstLastBenchmarks.cs ├── ListLoopBenchmarks.cs ├── ListSizeBenchmarks.cs ├── OrderBenchmarks.cs ├── Practical.BenchmarkDotNet.csproj ├── Program.cs ├── ReflectionMethodBenchmarks.cs ├── ReflectionPropertyBenchmarks.cs ├── ReflectionVsUnsafeAccessorBenchmarks.cs ├── RegexBenchmarks.cs ├── StopWatchBenchmarks.cs ├── StringContainsBenchmarks.cs ├── StringEndsWithBenchmarks.cs ├── StringStartsWithBenchmarks.cs ├── TryParseStringIsNullOrEmptyBenchmarks.cs └── TryParseVsTryCatchParseBenchmarks.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Phong Nguyen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Practical.BenchmarkDotNet -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32516.85 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Practical.BenchmarkDotNet", "Practical.BenchmarkDotNet\Practical.BenchmarkDotNet.csproj", "{2394971F-B3E3-4D40-8F6A-E4FF829781BE}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {2394971F-B3E3-4D40-8F6A-E4FF829781BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {2394971F-B3E3-4D40-8F6A-E4FF829781BE}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {2394971F-B3E3-4D40-8F6A-E4FF829781BE}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {2394971F-B3E3-4D40-8F6A-E4FF829781BE}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {500A793F-EB1B-4720-916F-7592BD392ECF} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ArrayBoundsCheckBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class ArrayBoundsCheckBenchmarks 7 | { 8 | private const int SIZE = 1_000_000; 9 | private static readonly string[] _array = new string[SIZE]; 10 | 11 | static ArrayBoundsCheckBenchmarks() 12 | { 13 | var random = new Random(2024); 14 | 15 | for (int i = 0; i < SIZE; i++) 16 | { 17 | _array[i] = random.Next().ToString(); 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public string BoundsCheckEnabled() 23 | { 24 | var result = string.Empty; 25 | 26 | for (int i = 0; i < _array.Length; i++) 27 | { 28 | result = _array[i]; 29 | } 30 | 31 | return result; 32 | } 33 | 34 | [Benchmark] 35 | public string BoundsCheckDisabled() 36 | { 37 | var array = _array; 38 | var result = string.Empty; 39 | 40 | for (int i = 0; i < array.Length; i++) 41 | { 42 | result = array[i]; 43 | } 44 | 45 | return result; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ArrayCopyBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class ArrayCopyBenchmarks 7 | { 8 | private const int SIZE = 1_000_000; 9 | private static readonly int[] _array = new int[SIZE]; 10 | 11 | static ArrayCopyBenchmarks() 12 | { 13 | var random = new Random(2024); 14 | 15 | for (int i = 0; i < SIZE; i++) 16 | { 17 | _array[i] = random.Next(); 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public void Loop() 23 | { 24 | var newArray = new int[SIZE]; 25 | 26 | for (int i = 0; i < SIZE; i++) 27 | { 28 | newArray[i] = _array[i]; 29 | } 30 | } 31 | 32 | [Benchmark] 33 | public void ArrayCopy() 34 | { 35 | var newArray = new int[SIZE]; 36 | 37 | Array.Copy(_array, newArray, SIZE); 38 | } 39 | 40 | [Benchmark] 41 | public void LinqSelectToArray() 42 | { 43 | var newArray = _array.Select(x => x).ToArray(); 44 | } 45 | 46 | [Benchmark] 47 | public void LinqToArray() 48 | { 49 | var newArray = _array.ToArray(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ArrayFirstLastBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class ArrayFirstLastBenchmarks 7 | { 8 | private const int SIZE = 1_000_000; 9 | private static readonly int[] _array = new int[SIZE]; 10 | 11 | static ArrayFirstLastBenchmarks() 12 | { 13 | var random = new Random(2024); 14 | 15 | for (int i = 0; i < SIZE; i++) 16 | { 17 | _array[i] = random.Next(); 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public void FirstUsingLinq() 23 | { 24 | _ = _array.First(); 25 | } 26 | 27 | [Benchmark] 28 | public void FirstUsingIndex() 29 | { 30 | _ = _array[0]; 31 | } 32 | 33 | [Benchmark] 34 | public void LastUsingLinq() 35 | { 36 | _ = _array.Last(); 37 | } 38 | 39 | [Benchmark] 40 | public void LastUsingIndex() 41 | { 42 | _ = _array[_array.Length - 1]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ArrayLoopBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class ArrayLoopBenchmarks 7 | { 8 | private const int SIZE = 1_000_000; 9 | private static readonly string[] _array = new string[SIZE]; 10 | 11 | static ArrayLoopBenchmarks() 12 | { 13 | var random = new Random(2024); 14 | 15 | for (int i = 0; i < SIZE; i++) 16 | { 17 | _array[i] = random.Next().ToString(); 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public string For() 23 | { 24 | var array = _array; 25 | var result = string.Empty; 26 | 27 | for (int i = 0; i < array.Length; i++) 28 | { 29 | result = array[i]; 30 | } 31 | 32 | return result; 33 | } 34 | 35 | [Benchmark] 36 | public string Foreach() 37 | { 38 | var array = _array; 39 | var result = string.Empty; 40 | 41 | foreach (var item in array) 42 | { 43 | result = item; 44 | } 45 | 46 | return result; 47 | } 48 | 49 | [Benchmark] 50 | public string ForEachMethod() 51 | { 52 | var array = _array; 53 | var result = string.Empty; 54 | 55 | Array.ForEach(array, item => result = item); 56 | 57 | return result; 58 | } 59 | 60 | [Benchmark] 61 | public string While() 62 | { 63 | var array = _array; 64 | var result = string.Empty; 65 | var i = 0; 66 | 67 | while (i < array.Length) 68 | { 69 | result = array[i]; 70 | i++; 71 | } 72 | 73 | return result; 74 | } 75 | 76 | [Benchmark] 77 | public string DoWhile() 78 | { 79 | var array = _array; 80 | var result = string.Empty; 81 | var i = 0; 82 | 83 | do 84 | { 85 | result = array[i]; 86 | i++; 87 | } 88 | while (i < array.Length); 89 | 90 | return result; 91 | } 92 | 93 | [Benchmark] 94 | public string GoTo() 95 | { 96 | var array = _array; 97 | var result = string.Empty; 98 | var i = 0; 99 | 100 | Start: 101 | if (i < array.Length) 102 | { 103 | result = array[i]; 104 | i++; 105 | goto Start; 106 | } 107 | 108 | return result; 109 | } 110 | 111 | [Benchmark] 112 | public string Span() 113 | { 114 | var result = string.Empty; 115 | var span = _array.AsSpan(); 116 | 117 | for (int i = 0; i < span.Length; i++) 118 | { 119 | result = span[i]; 120 | } 121 | 122 | return result; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ArraySizeBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [WarmupCount(0)] 6 | [IterationCount(1)] 7 | [InvocationCount(1)] 8 | [MemoryDiagnoser] 9 | public class ArraySizeBenchmarks 10 | { 11 | [Benchmark] 12 | public void Bool() 13 | { 14 | var x = new bool[Array.MaxLength / 2]; 15 | } 16 | 17 | [Benchmark] 18 | public void Int() 19 | { 20 | var x = new int[Array.MaxLength / 2]; 21 | } 22 | 23 | [Benchmark] 24 | public void Float() 25 | { 26 | var x = new float[Array.MaxLength / 2]; 27 | } 28 | 29 | [Benchmark] 30 | public void Long() 31 | { 32 | var x = new long[Array.MaxLength / 2]; 33 | } 34 | 35 | [Benchmark] 36 | public void Decimal() 37 | { 38 | var x = new decimal[Array.MaxLength / 2]; 39 | } 40 | 41 | [Benchmark] 42 | public void String() 43 | { 44 | var x = new string[Array.MaxLength / 2]; 45 | } 46 | 47 | [Benchmark] 48 | public void Struct() 49 | { 50 | var x = new PersonStruct[Array.MaxLength / 2]; 51 | } 52 | 53 | [Benchmark] 54 | public void Class() 55 | { 56 | var x = new PersonClass[Array.MaxLength / 2]; 57 | } 58 | 59 | private struct PersonStruct 60 | { 61 | public int Int { get; set; } 62 | 63 | public decimal Decimal { get; set; } 64 | } 65 | 66 | private class PersonClass 67 | { 68 | public int Int { get; set; } 69 | 70 | public decimal Decimal { get; set; } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/CheckAlphanumericBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public partial class CheckAlphanumericBenchmarks 8 | { 9 | private static readonly Regex _regex = new Regex("^[a-zA-Z0-9]*$"); 10 | private const string LARGE = "fhalfhalkfhlkfhklahfklashfklashfklashflaskfhowiuroiywroywoiqryoqiwryiowy1321312o4yoi4y1oi4y1oi4y12oi4y1oi4y1o2i4y1o2i4y1oi4y12oi4y12oi4y12oi4y12oi4y1o2i4y12oi4yo12i4yo12i4y1o2i4y12io4y12io4y12io4y12io4y12io4y12io4yo12i4yo12i4y12io4y12io4y1412oi4y21oi4y12oi"; 11 | private const string LARGE_INPUT = LARGE + LARGE + LARGE + LARGE; 12 | private const string LARGE_INPUT2 = LARGE_INPUT + "#"; 13 | 14 | [Params("abc", "123", "abc/", LARGE_INPUT, LARGE_INPUT2)] 15 | public string Input { get; set; } 16 | 17 | [Benchmark] 18 | public bool IsLetterOrDigit() 19 | { 20 | foreach (char c in Input) 21 | { 22 | if (!char.IsLetterOrDigit(c)) 23 | { 24 | return false; 25 | } 26 | } 27 | return true; 28 | } 29 | 30 | [Benchmark] 31 | public bool Regex() 32 | { 33 | var regex = new Regex("^[a-zA-Z0-9]*$"); 34 | return regex.IsMatch(Input); 35 | } 36 | 37 | [Benchmark] 38 | public bool CachedRegex() 39 | { 40 | return _regex.IsMatch(Input); 41 | } 42 | 43 | [Benchmark] 44 | public bool GeneratedRegex() 45 | { 46 | return AlphanumericGeneratedRegex().IsMatch(Input); 47 | } 48 | 49 | [GeneratedRegex("^[a-zA-Z0-9]*$")] 50 | private static partial Regex AlphanumericGeneratedRegex(); 51 | } 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/DictionaryBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class DictionaryBenchmarks 7 | { 8 | [Params("123", "abc")] 9 | public string Input { get; set; } 10 | 11 | private static readonly Dictionary _dic = new Dictionary { { "abc", "" } }; 12 | 13 | [Benchmark] 14 | public void TryGetValue() 15 | { 16 | if (_dic.TryGetValue(Input, out string result)) 17 | { 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public void ContainsKey() 23 | { 24 | if (_dic.ContainsKey(Input)) 25 | { 26 | var result = _dic[Input]; 27 | } 28 | } 29 | 30 | [Benchmark] 31 | public void TryCatch() 32 | { 33 | try 34 | { 35 | var result = _dic[Input]; 36 | } 37 | catch(KeyNotFoundException) 38 | { 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/DictionaryLookupVsPatternMatchingBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class DictionaryLookupVsPatternMatchingBenchmarks 7 | { 8 | private static readonly Dictionary _sharedDic = new() 9 | { 10 | { "VN", "Viet Nam" }, 11 | { "US", "United States" }, 12 | { "GB", "Great Britain" } 13 | }; 14 | 15 | [Benchmark] 16 | public void DictionaryLookup() 17 | { 18 | var dic = new Dictionary 19 | { 20 | { "VN", "Viet Nam" }, 21 | { "US", "United States" }, 22 | { "GB", "Great Britain" } 23 | }; 24 | 25 | var country = dic["US"]; 26 | } 27 | 28 | [Benchmark] 29 | public void SharedDictionaryLookup() 30 | { 31 | var country = _sharedDic["US"]; 32 | } 33 | 34 | [Benchmark] 35 | public void PatternMatching() 36 | { 37 | var country = GetCountry("US"); 38 | } 39 | 40 | private static string GetCountry(string code) 41 | { 42 | return code switch 43 | { 44 | "VN" => "Viet Nam", 45 | "US" => "United States", 46 | "GB" => "Great Britain", 47 | _ => throw new ArgumentException("Invalid Code", nameof(code)), 48 | }; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/DictionaryLoopBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public class DictionaryLoopBenchmarks 8 | { 9 | private static readonly Dictionary _peopleDic = new Dictionary(); 10 | private static readonly List _peopleList = new(1_000_000); 11 | 12 | static DictionaryLoopBenchmarks() 13 | { 14 | var random = new Random(2024); 15 | 16 | for (int i = 0; i < 1_000_000; i++) 17 | { 18 | var person = new Person { Id = i, Age = random.Next() }; 19 | _peopleList.Add(person); 20 | _peopleDic[person.Id] = person; 21 | } 22 | } 23 | 24 | [Benchmark] 25 | public void DictionaryLookup() 26 | { 27 | int personId = 999_999; 28 | var person = _peopleDic[personId]; 29 | } 30 | 31 | [Benchmark] 32 | public void ListLookup() 33 | { 34 | int personId = 999_999; 35 | var person = _peopleList.First(x => x.Id == personId); 36 | } 37 | 38 | [Benchmark] 39 | public void DictionaryLoop() 40 | { 41 | var count = _peopleDic.Count(x => x.Value.Age > 18); 42 | } 43 | 44 | [Benchmark] 45 | public void DictionaryValuesLoop() 46 | { 47 | var count = _peopleDic.Values.Count(x => x.Age > 18); 48 | } 49 | 50 | [Benchmark] 51 | public void ListLoop() 52 | { 53 | var count = _peopleList.Count(x => x.Age > 18); 54 | } 55 | 56 | [Benchmark] 57 | public void ListAsSpanLoop() 58 | { 59 | var span = CollectionsMarshal.AsSpan(_peopleList); 60 | int count = 0; 61 | 62 | foreach (var person in span) 63 | { 64 | if (person.Age > 18) 65 | { 66 | count++; 67 | } 68 | } 69 | } 70 | 71 | 72 | public class Person 73 | { 74 | public int Id { get; set; } 75 | 76 | public int Age { get; set; } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/FrozenDictionaryBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Collections.Frozen; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public class FrozenDictionaryBenchmarks 8 | { 9 | private static readonly List _peopleList = new(1_000); 10 | private static readonly Dictionary _dic; 11 | private static readonly FrozenDictionary _frozenDic; 12 | 13 | static FrozenDictionaryBenchmarks() 14 | { 15 | var random = new Random(2024); 16 | 17 | for (int i = 0; i < 1_000; i++) 18 | { 19 | var person = new Person { Id = i, Age = random.Next() }; 20 | _peopleList.Add(person); 21 | } 22 | 23 | _dic = _peopleList.ToDictionary(x => x.Id, x => x); 24 | _frozenDic = _peopleList.ToFrozenDictionary(x => x.Id, x => x); 25 | } 26 | 27 | [Benchmark] 28 | public void ToDictionary() 29 | { 30 | var dic = _peopleList.ToDictionary(x => x.Id, x => x); 31 | } 32 | 33 | [Benchmark] 34 | public void ToFrozenDictionary() 35 | { 36 | var dic = _peopleList.ToFrozenDictionary(x => x.Id, x => x); 37 | } 38 | 39 | [Benchmark] 40 | public void Dictionary_ContainsKey() 41 | { 42 | var x = _dic.ContainsKey(999); 43 | } 44 | 45 | [Benchmark] 46 | public void FrozenDictionary_ContainsKey() 47 | { 48 | var x = _frozenDic.ContainsKey(999); 49 | } 50 | 51 | [Benchmark] 52 | public void Dictionary_TryGetValue() 53 | { 54 | var x = _dic.TryGetValue(999, out var person); 55 | } 56 | 57 | [Benchmark] 58 | public void FrozenDictionary_TryGetValue() 59 | { 60 | var x = _frozenDic.TryGetValue(999, out var person); 61 | } 62 | 63 | [Benchmark] 64 | public void Dictionary_Indexer() 65 | { 66 | var person = _dic[999]; 67 | } 68 | 69 | [Benchmark] 70 | public void FrozenDictionary_Indexer() 71 | { 72 | var person = _frozenDic[999]; 73 | } 74 | 75 | public class Person 76 | { 77 | public int Id { get; set; } 78 | 79 | public int Age { get; set; } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/HashBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using CryptographyHelper; 3 | using CryptographyHelper.HashAlgorithms; 4 | 5 | namespace Practical.BenchmarkDotNet; 6 | 7 | [MemoryDiagnoser] 8 | public class HashBenchmarks 9 | { 10 | [Benchmark] 11 | public void Md5() 12 | { 13 | const string originalMessage = "Original Message to hash"; 14 | var hashed = originalMessage.UseMd5().ComputeHash().ToHexString(); 15 | } 16 | 17 | [Benchmark] 18 | public void Sha1() 19 | { 20 | const string originalMessage = "Original Message to hash"; 21 | var hashed = originalMessage.UseSha1().ComputeHash().ToHexString(); 22 | } 23 | 24 | [Benchmark] 25 | public void Sha256() 26 | { 27 | const string originalMessage = "Original Message to hash"; 28 | var hashed = originalMessage.UseSha256().ComputeHash().ToHexString(); 29 | } 30 | 31 | [Benchmark] 32 | public void Sha384() 33 | { 34 | const string originalMessage = "Original Message to hash"; 35 | var hashed = originalMessage.UseSha384().ComputeHash().ToHexString(); 36 | } 37 | 38 | [Benchmark] 39 | public void Sha512() 40 | { 41 | const string originalMessage = "Original Message to hash"; 42 | var hashed = originalMessage.UseSha512().ComputeHash().ToHexString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/JsonDeserializeBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Text.Json; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [WarmupCount(0)] 7 | [IterationCount(1)] 8 | [InvocationCount(1)] 9 | [MemoryDiagnoser] 10 | public class JsonDeserializeBenchmarks 11 | { 12 | private static readonly HttpClient _httpClient = new HttpClient(); 13 | private HttpResponseMessage _httpResponseMessage1; 14 | private HttpResponseMessage _httpResponseMessage2; 15 | 16 | static JsonDeserializeBenchmarks() 17 | { 18 | _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"); 19 | } 20 | 21 | [IterationSetup] 22 | public void Setup() 23 | { 24 | var url = $"https://api.github.com/repos/phongnguyend/Practical.BenchmarkDotNet"; 25 | 26 | _httpResponseMessage1 = _httpClient.GetAsync(url).GetAwaiter().GetResult(); 27 | _httpResponseMessage2 = _httpClient.GetAsync(url).GetAwaiter().GetResult(); 28 | } 29 | 30 | [Benchmark] 31 | public async Task StringDeserialize() 32 | { 33 | var json = await _httpResponseMessage1.Content.ReadAsStringAsync(); 34 | var response = JsonSerializer.Deserialize(json); 35 | } 36 | 37 | [Benchmark] 38 | public async Task StreamDeserialize() 39 | { 40 | var stream = await _httpResponseMessage2.Content.ReadAsStreamAsync(); 41 | var response = JsonSerializer.Deserialize(stream); 42 | } 43 | 44 | private class ApiRepsonse 45 | { 46 | public int stargazers_count { get; set; } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/JsonSerializerOptionsBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Text.Json; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public class JsonSerializerOptionsBenchmarks 8 | { 9 | [Params("{}")] 10 | public string Input { get; set; } 11 | 12 | [Benchmark] 13 | public void NoOptions() 14 | { 15 | for (var i = 0; i < 1_000; i++) 16 | { 17 | JsonSerializer.Serialize(Input); 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public void NewOptions() 23 | { 24 | for (var i = 0; i < 1_000; i++) 25 | { 26 | JsonSerializer.Serialize(Input, new JsonSerializerOptions()); 27 | } 28 | } 29 | 30 | [Benchmark] 31 | public void ReuseOptions() 32 | { 33 | 34 | var options = new JsonSerializerOptions(); 35 | 36 | for (var i = 0; i < 1_000; i++) 37 | { 38 | JsonSerializer.Serialize(Input, options); 39 | } 40 | } 41 | 42 | private static readonly JsonSerializerOptions _options = new(); 43 | 44 | [Benchmark] 45 | public void ReuseStaticOptions() 46 | { 47 | for (var i = 0; i < 1_000; i++) 48 | { 49 | JsonSerializer.Serialize(Input, _options); 50 | } 51 | } 52 | } 53 | 54 | /* 55 | https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/configure-options?pivots=dotnet-8-0#reuse-jsonserializeroptions-instances 56 | */ -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ListCopyBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class ListCopyBenchmarks 7 | { 8 | private const int SIZE = 1_000_000; 9 | private static readonly List _list = new List(SIZE); 10 | 11 | static ListCopyBenchmarks() 12 | { 13 | var random = new Random(2024); 14 | 15 | for (int i = 0; i < SIZE; i++) 16 | { 17 | _list.Add(random.Next()); 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public void LoopAdd() 23 | { 24 | var newList = new List(); 25 | 26 | for (int i = 0; i < SIZE; i++) 27 | { 28 | newList.Add(_list[i]); 29 | } 30 | } 31 | 32 | [Benchmark] 33 | public void LoopAddCapacity() 34 | { 35 | var newList = new List(SIZE); 36 | 37 | for (int i = 0; i < SIZE; i++) 38 | { 39 | newList.Add(_list[i]); 40 | } 41 | } 42 | 43 | [Benchmark] 44 | public void AddRange() 45 | { 46 | var newList = new List(); 47 | newList.AddRange(_list); 48 | } 49 | 50 | [Benchmark] 51 | public void AddRangeCapacity() 52 | { 53 | var newList = new List(SIZE); 54 | newList.AddRange(_list); 55 | } 56 | 57 | [Benchmark] 58 | public void CopyConstructor() 59 | { 60 | var newList = new List(_list); 61 | } 62 | 63 | [Benchmark] 64 | public void LinqSelectToList() 65 | { 66 | var newArray = _list.Select(x => x).ToList(); 67 | } 68 | 69 | [Benchmark] 70 | public void LinqToList() 71 | { 72 | var newArray = _list.ToList(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ListFirstLastBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class ListFirstLastBenchmarks 7 | { 8 | private const int SIZE = 1_000_000; 9 | private static readonly List _list = new List(SIZE); 10 | 11 | static ListFirstLastBenchmarks() 12 | { 13 | var random = new Random(2024); 14 | 15 | for (int i = 0; i < SIZE; i++) 16 | { 17 | _list.Add(random.Next()); 18 | } 19 | } 20 | 21 | [Benchmark] 22 | public void FirstUsingLinq() 23 | { 24 | _ = _list.First(); 25 | } 26 | 27 | [Benchmark] 28 | public void FirstUsingIndex() 29 | { 30 | _ = _list[0]; 31 | } 32 | 33 | [Benchmark] 34 | public void LastUsingLinq() 35 | { 36 | _ = _list.Last(); 37 | } 38 | 39 | [Benchmark] 40 | public void LastUsingIndex() 41 | { 42 | _ = _list[_list.Count - 1]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ListLoopBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public class ListLoopBenchmarks 8 | { 9 | private const int SIZE = 1_000_000; 10 | private static readonly List _list = new List(SIZE); 11 | 12 | static ListLoopBenchmarks() 13 | { 14 | var random = new Random(2024); 15 | 16 | for (int i = 0; i < SIZE; i++) 17 | { 18 | _list.Add(random.Next().ToString()); 19 | } 20 | } 21 | 22 | [Benchmark] 23 | public string For() 24 | { 25 | var list = _list; 26 | var result = string.Empty; 27 | 28 | for (int i = 0; i < list.Count; i++) 29 | { 30 | result = list[i]; 31 | } 32 | 33 | return result; 34 | } 35 | 36 | [Benchmark] 37 | public string Foreach() 38 | { 39 | var list = _list; 40 | var result = string.Empty; 41 | 42 | foreach (var item in list) 43 | { 44 | result = item; 45 | } 46 | 47 | return result; 48 | } 49 | 50 | [Benchmark] 51 | public string ForEachMethod() 52 | { 53 | var list = _list; 54 | var result = string.Empty; 55 | 56 | list.ForEach(item => result = item); 57 | 58 | return result; 59 | } 60 | 61 | [Benchmark] 62 | public string While() 63 | { 64 | var list = _list; 65 | var result = string.Empty; 66 | var i = 0; 67 | 68 | while (i < list.Count) 69 | { 70 | result = list[i]; 71 | i++; 72 | } 73 | 74 | return result; 75 | } 76 | 77 | [Benchmark] 78 | public string DoWhile() 79 | { 80 | var list = _list; 81 | var result = string.Empty; 82 | var i = 0; 83 | 84 | do 85 | { 86 | result = list[i]; 87 | i++; 88 | } 89 | while (i < list.Count); 90 | 91 | return result; 92 | } 93 | 94 | [Benchmark] 95 | public string GoTo() 96 | { 97 | var list = _list; 98 | var result = string.Empty; 99 | var i = 0; 100 | 101 | Start: 102 | if (i < list.Count) 103 | { 104 | result = list[i]; 105 | i++; 106 | goto Start; 107 | } 108 | 109 | return result; 110 | } 111 | 112 | [Benchmark] 113 | public string Span() 114 | { 115 | var result = string.Empty; 116 | var span = CollectionsMarshal.AsSpan(_list); 117 | 118 | for (int i = 0; i < span.Length; i++) 119 | { 120 | result = span[i]; 121 | } 122 | 123 | return result; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ListSizeBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [WarmupCount(0)] 6 | [IterationCount(1)] 7 | [InvocationCount(1)] 8 | [MemoryDiagnoser] 9 | public class ListSizeBenchmarks 10 | { 11 | [Benchmark] 12 | public void Bool() 13 | { 14 | var x = new List(Array.MaxLength / 2); 15 | } 16 | 17 | [Benchmark] 18 | public void Int() 19 | { 20 | var x = new List(Array.MaxLength / 2); 21 | } 22 | 23 | [Benchmark] 24 | public void Float() 25 | { 26 | var x = new List(Array.MaxLength / 2); 27 | } 28 | 29 | [Benchmark] 30 | public void Long() 31 | { 32 | var x = new List(Array.MaxLength / 2); 33 | } 34 | 35 | [Benchmark] 36 | public void Decimal() 37 | { 38 | var x = new List(Array.MaxLength / 2); 39 | } 40 | 41 | [Benchmark] 42 | public void String() 43 | { 44 | var x = new List(Array.MaxLength / 2); 45 | } 46 | 47 | [Benchmark] 48 | public void Struct() 49 | { 50 | var x = new List(Array.MaxLength / 2); 51 | } 52 | 53 | [Benchmark] 54 | public void Class() 55 | { 56 | var x = new List(Array.MaxLength / 2); 57 | } 58 | 59 | private struct PersonStruct 60 | { 61 | public int Int { get; set; } 62 | 63 | public decimal Decimal { get; set; } 64 | } 65 | 66 | private class PersonClass 67 | { 68 | public int Int { get; set; } 69 | 70 | public decimal Decimal { get; set; } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/OrderBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class OrderBenchmarks 7 | { 8 | private readonly int _size = 1_000; 9 | 10 | [Benchmark] 11 | public List LINQ_Order() 12 | { 13 | var random = new Random(2024); 14 | var list = new List(_size); 15 | 16 | for (int i = 0; i < _size; i++) 17 | { 18 | list.Add(random.Next()); 19 | } 20 | 21 | return list.Order().ToList(); 22 | } 23 | 24 | [Benchmark] 25 | public List LINQ_OrderBy() 26 | { 27 | var random = new Random(2024); 28 | var list = new List(_size); 29 | 30 | for (int i = 0; i < _size; i++) 31 | { 32 | list.Add(random.Next()); 33 | } 34 | 35 | return list.OrderBy(x => x).ToList(); 36 | } 37 | 38 | [Benchmark] 39 | public List List_Sort() 40 | { 41 | var random = new Random(2024); 42 | var list = new List(_size); 43 | 44 | for (int i = 0; i < _size; i++) 45 | { 46 | list.Add(random.Next()); 47 | } 48 | 49 | list.Sort(); 50 | 51 | return list; 52 | } 53 | 54 | [Benchmark] 55 | public List LINQ_OrderDescending() 56 | { 57 | var random = new Random(2024); 58 | var list = new List(_size); 59 | 60 | for (int i = 0; i < _size; i++) 61 | { 62 | list.Add(random.Next()); 63 | } 64 | 65 | return list.OrderDescending().ToList(); 66 | } 67 | 68 | [Benchmark] 69 | public List LINQ_OrderByDescending() 70 | { 71 | var random = new Random(2024); 72 | var list = new List(_size); 73 | 74 | for (int i = 0; i < _size; i++) 75 | { 76 | list.Add(random.Next()); 77 | } 78 | 79 | return list.OrderByDescending(x => x).ToList(); 80 | } 81 | 82 | [Benchmark] 83 | public List List_SortDescending() 84 | { 85 | var random = new Random(2024); 86 | var list = new List(_size); 87 | 88 | for (int i = 0; i < _size; i++) 89 | { 90 | list.Add(random.Next()); 91 | } 92 | 93 | list.Sort((a, b) => b.CompareTo(a)); 94 | 95 | return list; 96 | } 97 | 98 | [Benchmark] 99 | public List List_SortAndReverse() 100 | { 101 | var random = new Random(2024); 102 | var list = new List(_size); 103 | 104 | for (int i = 0; i < _size; i++) 105 | { 106 | list.Add(random.Next()); 107 | } 108 | 109 | list.Sort(); 110 | list.Reverse(); 111 | 112 | return list; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | using Practical.BenchmarkDotNet; 3 | 4 | _ = BenchmarkRunner.Run(); 5 | //_ = BenchmarkRunner.Run(); 6 | //_ = BenchmarkRunner.Run(); 7 | //_ = BenchmarkRunner.Run(); 8 | //_ = BenchmarkRunner.Run(); 9 | //_ = BenchmarkRunner.Run(); 10 | //_ = BenchmarkRunner.Run(); 11 | //_ = BenchmarkRunner.Run(); 12 | //_ = BenchmarkRunner.Run(); 13 | //_ = BenchmarkRunner.Run(); 14 | //_ = BenchmarkRunner.Run(); 15 | //_ = BenchmarkRunner.Run(); 16 | //_ = BenchmarkRunner.Run(); 17 | //_ = BenchmarkRunner.Run(); 18 | //_ = BenchmarkRunner.Run(); 19 | //_ = BenchmarkRunner.Run(); 20 | //_ = BenchmarkRunner.Run(); 21 | //_ = BenchmarkRunner.Run(); 22 | //_ = BenchmarkRunner.Run(); 23 | //_ = BenchmarkRunner.Run(); 24 | //_ = BenchmarkRunner.Run(); 25 | //_ = BenchmarkRunner.Run(); 26 | //_ = BenchmarkRunner.Run(); 27 | //_ = BenchmarkRunner.Run(); 28 | //_ = BenchmarkRunner.Run(); 29 | //_ = BenchmarkRunner.Run(); 30 | //_ = BenchmarkRunner.Run(); 31 | //_ = BenchmarkRunner.Run(); -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ReflectionMethodBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Reflection; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public class ReflectionMethodBenchmarks 8 | { 9 | private readonly Person _person = new Person { Id = 1 }; 10 | private static readonly MethodInfo _methodInfo = typeof(Person).GetMethod("SomeMethod"); 11 | private static readonly Func _methodDelegate = (Func)Delegate.CreateDelegate(typeof(Func), _methodInfo); 12 | 13 | [Benchmark] 14 | public void SomeMethod() 15 | { 16 | var rs = _person.SomeMethod(""); 17 | } 18 | 19 | [Benchmark] 20 | public void SomeMethodReflection() 21 | { 22 | var rs = typeof(Person).GetMethod("SomeMethod").Invoke(_person, [""]); 23 | } 24 | 25 | [Benchmark] 26 | public void SomeMethodReflectionCached() 27 | { 28 | var rs = _methodInfo.Invoke(_person, [""]); 29 | } 30 | 31 | [Benchmark] 32 | public void SomeMethodDelegate() 33 | { 34 | var rs = _methodDelegate(_person, ""); 35 | } 36 | 37 | public class Person 38 | { 39 | public int Id { get; set; } 40 | 41 | public string SomeMethod(string name) 42 | { 43 | return name; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ReflectionPropertyBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Reflection; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public class ReflectionPropertyBenchmarks 8 | { 9 | private readonly Person _person = new Person { Id = 1 }; 10 | private static readonly PropertyInfo _propertyInfo = typeof(Person).GetProperty("Id"); 11 | private static readonly Func _getIdDelegate = (Func)Delegate.CreateDelegate(typeof(Func), _propertyInfo.GetGetMethod()); 12 | private static readonly Action _setIdDelegate = (Action)Delegate.CreateDelegate(typeof(Action), _propertyInfo.GetSetMethod()); 13 | 14 | [Benchmark] 15 | public void GetId() 16 | { 17 | var id = _person.Id; 18 | } 19 | 20 | [Benchmark] 21 | public void GetIdReflection() 22 | { 23 | var id = (int)typeof(Person).GetProperty("Id").GetValue(_person); 24 | } 25 | 26 | [Benchmark] 27 | public void GetIdReflectionCached() 28 | { 29 | var id = (int)_propertyInfo.GetValue(_person); 30 | } 31 | 32 | [Benchmark] 33 | public void GetIdDelegate() 34 | { 35 | var id = _getIdDelegate(_person); 36 | } 37 | 38 | [Benchmark] 39 | public void SetId() 40 | { 41 | _person.Id = 2; 42 | } 43 | 44 | [Benchmark] 45 | public void SetIdReflection() 46 | { 47 | typeof(Person).GetProperty("Id").SetValue(_person, 2); 48 | } 49 | 50 | [Benchmark] 51 | public void SetIdReflectionCached() 52 | { 53 | _propertyInfo.SetValue(_person, 2); 54 | } 55 | 56 | [Benchmark] 57 | public void SetIdDelegate() 58 | { 59 | _setIdDelegate(_person, 2); 60 | } 61 | 62 | public class Person 63 | { 64 | public int Id { get; set; } 65 | 66 | public string SomeMethod(string name) 67 | { 68 | return name; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/ReflectionVsUnsafeAccessorBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Reflection; 3 | using System.Runtime.CompilerServices; 4 | 5 | namespace Practical.BenchmarkDotNet; 6 | 7 | [MemoryDiagnoser] 8 | public class ReflectionVsUnsafeAccessorBenchmarks 9 | { 10 | private readonly Person _person = new Person { Id = 1 }; 11 | private static readonly MethodInfo _methodInfo = typeof(Person).GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic); 12 | private static readonly Func _methodDelegate = (Func)Delegate.CreateDelegate(typeof(Func), _methodInfo); 13 | 14 | [Benchmark] 15 | public void PrivateMethodReflection() 16 | { 17 | var rs = typeof(Person).GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(_person, [""]); 18 | } 19 | 20 | [Benchmark] 21 | public void PrivateMethodReflectionCached() 22 | { 23 | var rs = _methodInfo.Invoke(_person, [""]); 24 | } 25 | 26 | [Benchmark] 27 | public void PrivateMethodDelegate() 28 | { 29 | var rs = _methodDelegate(_person, ""); 30 | } 31 | 32 | [Benchmark] 33 | public void PrivateMethodUnsafeAccessor() 34 | { 35 | var rs = PrivateMethod(_person, ""); 36 | } 37 | 38 | public class Person 39 | { 40 | public int Id { get; set; } 41 | 42 | private string PrivateMethod(string name) 43 | { 44 | return name; 45 | } 46 | } 47 | 48 | [UnsafeAccessor(UnsafeAccessorKind.Method)] 49 | extern static string PrivateMethod(Person person, string name); 50 | } 51 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/RegexBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public partial class RegexBenchmarks 8 | { 9 | private static readonly Regex _regex = new Regex("^[a-zA-Z0-9]*$"); 10 | private const string LARGE = "fhalfhalkfhlkfhklahfklashfklashfklashflaskfhowiuroiywroywoiqryoqiwryiowy1321312o4yoi4y1oi4y1oi4y12oi4y1oi4y1o2i4y1o2i4y1oi4y12oi4y12oi4y12oi4y12oi4y1o2i4y12oi4yo12i4yo12i4y1o2i4y12io4y12io4y12io4y12io4y12io4y12io4yo12i4yo12i4y12io4y12io4y1412oi4y21oi4y12oi"; 11 | private const string LARGE_INPUT = LARGE + LARGE + LARGE + LARGE; 12 | private const string LARGE_INPUT1 = "#" + LARGE_INPUT; 13 | private const string LARGE_INPUT2 = LARGE_INPUT + "#"; 14 | 15 | [Params("a1b2c", "/a1b2c", "a1b2c/", LARGE_INPUT, LARGE_INPUT1, LARGE_INPUT2)] 16 | public string Input { get; set; } 17 | 18 | [Benchmark] 19 | public bool Regex() 20 | { 21 | var regex = new Regex("^[a-zA-Z0-9]*$"); 22 | return regex.IsMatch(Input); 23 | } 24 | 25 | [Benchmark] 26 | public bool CachedRegex() 27 | { 28 | return _regex.IsMatch(Input); 29 | } 30 | 31 | [Benchmark] 32 | public bool GeneratedRegex() 33 | { 34 | return AlphanumericGeneratedRegex().IsMatch(Input); 35 | } 36 | 37 | [GeneratedRegex("^[a-zA-Z0-9]*$")] 38 | private static partial Regex AlphanumericGeneratedRegex(); 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/StopWatchBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Diagnostics; 3 | 4 | namespace Practical.BenchmarkDotNet; 5 | 6 | [MemoryDiagnoser] 7 | public class StopwatchBenchmarks 8 | { 9 | [Benchmark] 10 | public TimeSpan StartNew() 11 | { 12 | var watch = Stopwatch.StartNew(); 13 | 14 | DoWork(); 15 | 16 | return watch.Elapsed; 17 | } 18 | 19 | [Benchmark] 20 | public TimeSpan GetTimestamp() 21 | { 22 | var start = Stopwatch.GetTimestamp(); 23 | 24 | DoWork(); 25 | 26 | return Stopwatch.GetElapsedTime(start); 27 | } 28 | 29 | private void DoWork() 30 | { 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/StringContainsBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class StringContainsBenchmarks 7 | { 8 | [Params("abc", "/abc", "abc/")] 9 | public string Input { get; set; } 10 | 11 | [Benchmark] 12 | public void ContainsString() 13 | { 14 | Input.Contains("/"); 15 | } 16 | 17 | [Benchmark] 18 | public void ContainsChar() 19 | { 20 | Input.Contains('/'); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/StringEndsWithBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class StringEndsWithBenchmarks 7 | { 8 | [Params("abc", "/abc", "abc/")] 9 | public string Input { get; set; } 10 | 11 | [Benchmark] 12 | public void EndsWithString() 13 | { 14 | Input.EndsWith("/"); 15 | } 16 | 17 | [Benchmark] 18 | public void EndsWithChar() 19 | { 20 | Input.EndsWith('/'); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/StringStartsWithBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class StringStartsWithBenchmarks 7 | { 8 | [Params("abc", "/abc", "abc/")] 9 | public string Input { get; set; } 10 | 11 | [Benchmark] 12 | public void StartsWithString() 13 | { 14 | Input.StartsWith("/"); 15 | } 16 | 17 | [Benchmark] 18 | public void StartsWithChar() 19 | { 20 | Input.StartsWith('/'); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/TryParseStringIsNullOrEmptyBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [ShortRunJob] 6 | [MemoryDiagnoser] 7 | public class TryParseStringIsNullOrEmptyBenchmarks 8 | { 9 | [Params("123", "abc", null, "", " ")] 10 | public string Input { get; set; } 11 | 12 | [Benchmark] 13 | public void TryParse() 14 | { 15 | if(int.TryParse(Input, out int result)) 16 | { 17 | } 18 | } 19 | 20 | [Benchmark] 21 | public void IsNullOrEmpty() 22 | { 23 | if (!string.IsNullOrEmpty(Input) && int.TryParse(Input, out int result)) 24 | { 25 | } 26 | } 27 | 28 | [Benchmark] 29 | public void IsNullOrWhiteSpace() 30 | { 31 | if (!string.IsNullOrWhiteSpace(Input) && int.TryParse(Input, out int result)) 32 | { 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Practical.BenchmarkDotNet/Practical.BenchmarkDotNet/TryParseVsTryCatchParseBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace Practical.BenchmarkDotNet; 4 | 5 | [MemoryDiagnoser] 6 | public class TryParseVsTryCatchParseBenchmarks 7 | { 8 | [Params("123", "abc")] 9 | public string Input { get; set; } 10 | 11 | [Benchmark] 12 | public void TryParse() 13 | { 14 | if(int.TryParse(Input, out int result)) 15 | { 16 | } 17 | } 18 | 19 | [Benchmark] 20 | public void TryCatchParse() 21 | { 22 | try 23 | { 24 | int.Parse(Input); 25 | } 26 | catch 27 | { 28 | } 29 | } 30 | } 31 | --------------------------------------------------------------------------------