Created
December 10, 2023 19:41
-
-
Save AhmedMostafa16/0333cbebfdf29521230deac4747efea5 to your computer and use it in GitHub Desktop.
Try/Catch Benchmark
This file contains 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 BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using System; | |
public class ExceptionBenchmark | |
{ | |
private const int Iterations = 1000000; | |
[Benchmark] | |
public void MethodWithTryCatch() | |
{ | |
for (int i = 0; i < Iterations; i++) | |
{ | |
try | |
{ | |
// Simulate a CPU-intensive operation | |
var result = PerformCpuIntensiveOperation(); | |
} | |
catch (Exception ex) | |
{ | |
// Handle the exception (empty catch block in this example) | |
} | |
} | |
} | |
[Benchmark] | |
public void MethodWithoutTryCatch() | |
{ | |
for (int i = 0; i < Iterations; i++) | |
{ | |
// Simulate a CPU-intensive operation | |
var result = PerformCpuIntensiveOperation(); | |
} | |
} | |
private int PerformCpuIntensiveOperation() | |
{ | |
// Simulate a CPU-intensive operation (e.g., a complex calculation) | |
return 42; | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
var summary = BenchmarkRunner.Run<ExceptionBenchmark>(); | |
} | |
} |
This file contains 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 BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using System; | |
using System.Runtime.CompilerServices; | |
public class ExceptionBenchmark | |
{ | |
private const int Iterations = 1000000; | |
[Benchmark] | |
public void MethodWithTryCatch() | |
{ | |
for (int i = 0; i < Iterations; i++) | |
{ | |
try | |
{ | |
// Simulate a CPU-intensive operation | |
var result = PerformCpuIntensiveOperation(); | |
} | |
catch (Exception ex) | |
{ | |
// Handle the exception (empty catch block in this example) | |
} | |
} | |
} | |
[Benchmark] | |
public void MethodWithoutTryCatch() | |
{ | |
for (int i = 0; i < Iterations; i++) | |
{ | |
// Simulate a CPU-intensive operation | |
var result = PerformCpuIntensiveOperation(); | |
} | |
} | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
private int PerformCpuIntensiveOperation() | |
{ | |
// Simulate a CPU-intensive operation (e.g., a complex calculation) | |
return 42; | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
var summary = BenchmarkRunner.Run<ExceptionBenchmark>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment