In algorithms we often have methods that return a single value. It is tempting to use a ref or out parameter in C# here.
using System;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
int temp;
Method1(
"", out temp);
Method2(
"");
// Version 1: use out return parameter.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int result;
Method1(
"cat", out result);
if (result != 6)
{
throw new Exception();
}
}
s1.Stop();
// Version 2: use single return value.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int result = Method2(
"cat");
if (result != 6)
{
throw new Exception();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
static void Method1(string test, out int result)
{
// Return value as an out parameter.
result = 0;
for (int i = 0; i < test.Length; i++)
{
result += 2;
}
}
static int Method2(string test)
{
// Return value with return statement.
int result = 0;
for (int i = 0; i < test.Length; i++)
{
result += 2;
}
return result;
}
}
2.03 ns
1.25 ns
2.08 ns
1.25 ns
2.03 ns
1.25 ns
Averages:
2.05 ns Method, out
1.25 ns Method, return