C# Local Variable Field Optimization

This C# program uses local variables instead of fields to optimize performance.

Local variable field. 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.

Tip: This optimization uses local variables that copy fields—and then are copied to fields.

 

 

Example. To start, this program shows how to directly modify a static field. It then shows to copy the field value to a local variable of the same type and then modify that local variable.

Static Field

 

Here: The methods Method1 and Method2 show how to directly modify the field and how to cache the field value.

C# program that benchmarks fields and locals

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 ns

Method2 required only about five nanoseconds. Method1 took more than three times as long. Copying a field to a local variable, changing the local variable, and then copying the value to the original location is sometimes more efficient.

 

Discussion. In optimizing computer programs written in high-level languages, code that requires more lines is sometimes more efficient. There is an uncertain correlation between the length of the source code and that of the instruction stream.

 

Further: Instructions have different latencies in the memory hierarchy and require varying times, even unpredictable times.

 

Summary. We saw 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.

 

And: Local variables are most likely stored in registers. Fields (stored in a heap memory location) are slower to access.

Memory Hierarchy: Performance Optimization