
A field can be copied into a local variable. Fields provide a way to persist a value into a memory storage outside of a procedure call. But they require additional indirections at the level of the machine memory to address. Using local variables that copy fields—and then are copied to fields—is sometimes more efficient.

To start, this program text demonstrates how you can directly modify a static field, and then how you can copy the field value to a local variable of the same type and then modify that local variable. The methods Method1 and Method2 show how to directly modify the field and how to cache the field value, respectively, and their performance per call is shown afterwards.
This C# program uses local variables instead of fields to optimize performance.
Program that benchmarks fields and locals [C#]
using System;
using System.Diagnostics;
class Program
{
static int _temp1; // Static field
static void Method1()
{
// Increment the static field ten times.
for (int i = 0; i < 10; i++)
{
_temp1++;
}
}
static void Method2()
{
// Load static field into variable.
// ... Increment that ten times, then copy the value.
int copy = _temp1;
for (int i = 0; i < 10; i++)
{
copy++;
}
_temp1 = copy;
}
// === Start benchmark code
const int _max = 1000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method1();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method2();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000)
/ _max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000)
/ _max).ToString("0.00 ns"));
Console.Read();
}
}
Output
15.86 ns
5.18 nsUsing local variable is faster than static field. The results of this execution is that the method Method2 required only about five nanoseconds to execute, while Method1 took more than three times as long. This means that copying a field to a local variable, and changing the local variable, and then copying the value to the original location is more efficient in cases such as this one.

In optimizing computer programs written in high-level code, code that requires more lines is sometimes more efficient. This is because there is an uncertain correlation between the length of the high-level source code and the length of the instruction stream generated; further, instructions have different latencies in the memory hierarchy and require varying times, even unpredictable times.

In this optimization problem, we looked at how in the C# language storing a field into a local variable cache of the same type can improve efficiency. At some level, this relates directly to the concept of the memory hierarchy in computer science. Local variables are most likely stored in registers, while fields are stored in a heap memory location and are slower to access.
Memory Hierarchy Method Tips