I've always written for
loops in C# using for (int i = 0; i < 10; i++)
.
I've been reading up on the best-practices for JavaScript (JavaScript: The Good Parts), and one of them is to prefer x += 1
over x++
.
Are there any differences, in C#, between the two in areas such as performance, atomicity, and functionality.
I ask, because there are functional differences between ++x
and x++
in C# (and C++ and probably most other C based languages); the former being pre-increment where it increments the variable and then returns the value, and the latter being post-increment where it returns the value and then increments it (actually, these two subtle differences are what's piqued my interest in adopting the x += 1
strategy in my C# code)
Update:
Here's two methods, method1
uses ++x
and method2
uses x += 1
:
static void method1()
{
int x = 1;
int y = ++x;
Console.WriteLine(x);
Console.WriteLine(y);
}
static void method2()
{
int x = 1;
int y = x += 1;
Console.WriteLine(x);
Console.WriteLine(y);
}
This produces the following IL:
Method 1:
Method 2:
There appears to be some minor differences, but my understanding of IL isn't enough to answer the question 'are there any differences'.
No difference at all. The Intermediate Language translated from
x += 1
andx++
is identical:The IL code is: