C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: A method that uses assignment to store the results of internal method calls can be rewritten as an expression-based method.
UseExpression: This method places the result of the Value1 and Value2 methods onto the evaluation stack for processing.
UseLocals: This places the results into local variable slots and then into the evaluation stack. It uses several local variable slots.
C# program that tests assignment and variables
using System;
class Program
{
static int _field = 5;
static int Value1()
{
// This method just returns an integer.
return _field * 2;
}
static int Value2()
{
// This method also returns an integer.
return _field * 3;
}
static int UseExpression()
{
// This method uses an expression-based statement.
// ... No temporary variables are needed here.
return Value1() +
Value2() +
Value1() +
Value2();
}
static int UseLocals()
{
// This method uses four variables to store intermediate values.
// ... These require storage locations.
int value1 = Value1();
int value2 = Value2();
int value3 = Value1();
int value4 = Value2();
return value1 + value2 + value3 + value4;
}
static void Main()
{
// Test the methods.
Console.WriteLine(UseExpression());
Console.WriteLine(UseLocals());
}
}
Output
50
50
Version 1: This code calls the UseExpression method. It avoids local variables, and computes a value.
Version 2: This version of the code uses the same logic as UseExpression, but uses several local variables to perform the computation.
Result: It is faster to avoid local variables. Even in these small methods, avoiding locals and assignments tends to be faster.
C# program that benchmarks assignment optimization
using System;
using System.Diagnostics;
class Program
{
static int _field = 5;
static int Value1()
{
return _field * 2;
}
static int Value2()
{
return _field * 3;
}
static int UseExpression()
{
return Value1() +
Value2() +
Value1() +
Value2();
}
static int UseLocals()
{
int value1 = Value1();
int value2 = Value2();
int value3 = Value1();
int value4 = Value2();
return value1 + value2 + value3 + value4;
}
const int _max = 10000000;
static void Main()
{
// Version 1: use expression logic.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (UseExpression() == 0)
{
return;
}
}
s1.Stop();
// Version 2: use local variable logic.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (UseLocals() == 0)
{
return;
}
}
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"));
}
}
Output
2.01 ns UseExpression
2.47 ns UseLocals
Info: Assignment introduces the complexity of time into programs. A program can only be understood at a certain point.