TheDeveloperBlog.com


C# Preincrement Integers

Preincrement integers. A number is incremented with an operator. Two increment operators in the C# language are postincrement and preincrement. They have different meanings. It is important to choose the correct one for your program.

Preincrement

++i;

Postincrement

i++;


Example. First, we look at the postincrement operator. You should be familiar with the double-plus and double-minus operators. This example uses the two pluses at the end of the variable identifier to increment the integer.

Int

Note: You can sometimes combine assignments with preincrements. This can improve performance.

C# program that increments

class Program
{
    static int _x;

    static void Main()
    {
	// Add one.
	_x++;

	// Read in the value again.
	int count = _x;
    }
}


Example 2. We can preincrement an integer. There are some cases when accessing an integer is relatively slow. This can be the case with static variables and volatile member ints. Here's how you can use preincrement to do the same thing.

Program 2: C#

class Program
{
    static int _x;

    static void Main()
    {
	// Increment then assign.
	int count = ++_x;
    }
}


Benchmark. Here we look at a benchmark of the two versions of the code. I found that when all variables are easy to "optimize" for the compiler, there is no difference. If your int is another class, it's slower to use.

Lines of code in benchmark

//
// 1.
//
TestStatic._test++;
int z = TestStatic._test;

//
// 2.
//
int z = ++TestStatic._test;

Benchmark results

Method 1 postincrement: 3026 ms
Method 2 preincrement:  2574 ms

Also, you may be wondering if there is a performance difference between having the ++ at the start or end. Some programmers have said that preincrementing is faster than postincrementing, but I was unable to reproduce this.

Note: I understand that this comes from C++ and some old implementations of it.


Summary. We used pre-increment and post-increment on integers. You can combine increments and assigns. The compiler is unable to optimize for static members, so this is more efficient. Use the preincrement-assign pattern for better performance.

Tip: You can find more general information and examples on incrementing integers here.

Increment Int