I'm currently learning about operators and expressions in C# and I understood that if I want to increment the value of a variable by 5, I can do it in two different ways: a = a + 5
and a += 5
. Apparently, the second way is easier and faster to write and more pleasant to read. However, computer-wise, is a += 5
faster than a = a + 5
? Does it take less time to compile and execute than the longer version of the expression?
However, computer-wise, is a += 5 faster than a = a + 5?
Both are same, first(a += 5
) is equal to second a = a + 5
.
You may see:
An expression using the
+=
assignment operator, such asx += y
is equivalent tox = x + y
except that x is only evaluated once. The meaning of the + operator depends on the types of x and y (addition for numeric operands, concatenation for string operands, and so forth).
So it depends on type of a
and in those situations where multiple threads are accessing your variable a
you could get different results. But for most of the other case it would be same:
For code:
static void Main(string[] args)
{
int a = 10;
a += 5;
Console.WriteLine(a);
}
Build in Release Mode the IL is
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 14 (0xe)
.maxstack 2
.locals init ([0] int32 a)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.5
IL_0005: add
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call void [mscorlib]System.Console::WriteLine(int32)
IL_000d: ret
} // end of method Program::Main
Same IL is generated through code:
static void Main(string[] args)
{
int a = 10;
a = a + 5;
Console.WriteLine(a);
}
IL (same) is:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 14 (0xe)
.maxstack 2
.locals init ([0] int32 a)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.5
IL_0005: add
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call void [mscorlib]System.Console::WriteLine(int32)
IL_000d: ret
} // end of method Program::Main
a
is. –
Brabble That depends on what a
is. a = a + 5
evaluates a
twice. a += 5
evaluates a
exactly once.
If a
is an integer, that difference is likely not to matter in most cases, although not strictly all cases. If, for example, a
is accessed from multiple threads then the exact types and windows for race conditions can differ.
On top of that, if evaluating the expression causes side effects it's the difference between those side effects being observed once versus being observed twice. That can, under certain circumstances, be a big deal, possibly affecting the correctness of the code, not just its speed.
© 2022 - 2024 — McMap. All rights reserved.