C# Return Optimization: out Performance

Test the performance of the out-keyword and the return statement. Optimize returns.

Return optimization. In algorithms we often have methods that return a single value. It is tempting to use a ref or out parameter in C# here.Optimization

With a plain return statement, though, our performance is best. Here we see a benchmark that replaces an out parameter with a return.

Example program. Here we introduce two methods, Method1 and Method2. We spent a lot of time trying to name these methods. They both have the same logic and make their results available.
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

An analysis. As noted by many developers, fast C# code usually resembles C code. C is a wonderful language. You are using it right now by visiting this web page.

A summary. Micro-optimizations add up. For more complex programs, using small optimizations like this one can make a significant difference—if used in the right places.

When possible, use return statements. If a method returns just one value, return it—do not place it in a ref or out parameter. This will improve program performance.Parameters

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.