C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Method 1: This version uses the out keyword. The "result" is set and made available to the calling code.
Method 2: This method uses the return statement. It is a more traditional, C-like method. It performs better.
Result: The return-statement is faster. If we reorder the test so that Method2 precedes Method1, the result is similar.
C# program that benchmarks out, return
using System;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
int temp;
Method1("", out temp);
Method2("");
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();
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;
}
}
Output
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