Skip to content

Instantly share code, notes, and snippets.

@AhmedMostafa16
Created December 10, 2023 19:41
Show Gist options
  • Save AhmedMostafa16/0333cbebfdf29521230deac4747efea5 to your computer and use it in GitHub Desktop.
Save AhmedMostafa16/0333cbebfdf29521230deac4747efea5 to your computer and use it in GitHub Desktop.
Try/Catch Benchmark
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>();
}
}
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