Skip to content

Instantly share code, notes, and snippets.

@adamcarr
Created May 24, 2012 19:45
Show Gist options
  • Save adamcarr/2783793 to your computer and use it in GitHub Desktop.
Save adamcarr/2783793 to your computer and use it in GitHub Desktop.
Exception vs Out Parameter Benchmark
using System;
using System.Collections.Generic;
using System.Text;
namespace ExceptionVsOutParamBenchmark
{
class Program
{
static void Main(string[] args)
{
var numberOfIterations = 1000000;
var goodS1 = "Adam";
var goodS2 = "Carr";
var combinedGoodStrings = goodS1 + goodS2;
var badS1 = string.Empty;
string badS2 = null;
//benchmark for exceptions
var exceptionTime = Benchmark(() =>
{
var combinedString = StringCombiner.CombineString(goodS1, goodS2);
if (combinedGoodStrings != combinedString)
{
throw new Exception("Combination Failed");
}
try
{
StringCombiner.CombineString(badS1, badS2);
throw new Exception("Combination didn't fail and should have.");
}
catch (Exception)
{
}
},
numberOfIterations);
//benchmark for out parameters
var outParamTime = Benchmark(() =>
{
string combinedString;
if (
!StringCombiner.TryCombineString(goodS1, goodS2, out combinedString))
{
throw new Exception("Combination Failed");
}
string badCombinedString;
if (StringCombiner.TryCombineString(badS1, badS2, out badCombinedString))
{
throw new Exception("Combination didn't fail and should have.");
}
},
numberOfIterations);
var expenseCoefficientForExceptions = exceptionTime.Ticks/(decimal) outParamTime.Ticks;
Console.WriteLine("The expense of using excpetions is {0} times that compared to using out parameters.", expenseCoefficientForExceptions);
}
static TimeSpan Benchmark(Action task, int numberOfIterations)
{
var startTime = DateTime.Now;
Console.WriteLine("Benchmark started at: {0}", startTime);
for (int i = 0; i < numberOfIterations; i++)
{
task.Invoke();
}
var endTime = DateTime.Now;
Console.WriteLine("Benchmark ended at: {0}", endTime);
var elapsedTime = endTime.Subtract(startTime);
Console.WriteLine("Benchmark duration was {0} for {1:N} iterations.", elapsedTime, numberOfIterations);
return elapsedTime;
}
}
public static class StringCombiner
{
public static string CombineString(string s1, string s2)
{
if(string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2))
{
throw new Exception("s1 or s2 is null or empty");
}
return s1 + s2;
}
public static bool TryCombineString(string s1, string s2, out string result)
{
if (string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2))
{
result = string.Empty;
return false;
}
result = s1 + s2;
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment