从
MSDN library for +=:
Using this operator is almost the same as specifying result = result + expression,except that result is only evaluated once.
所以他们不是相同的,这就是为什么x = 1会更有效率。
更新:我只是注意到我的MSDN库链接到JScript页面而不是VB page,它不包含相同的报价。
因此,进一步的研究和测试,这个答案不适用于VB.NET。我错了。下面是一个示例控制台应用程序:
Module Module1 Sub Main() Dim x = 0 Console.WriteLine(PlusEqual1(x)) Console.WriteLine(Add1(x)) Console.WriteLine(PlusEqual2(x)) Console.WriteLine(Add2(x)) Console.ReadLine() End Sub Public Function PlusEqual1(ByVal x As Integer) As Integer x += 1 Return x End Function Public Function Add1(ByVal x As Integer) As Integer x = x + 1 Return x End Function Public Function PlusEqual2(ByVal x As Integer) As Integer x += 2 Return x End Function Public Function Add2(ByVal x As Integer) As Integer x = x + 2 Return x End Function End Module
IL对于PlusEqual1和Add1确实是相同的:
.method public static int32 Add1(int32 x) cil managed { .maxstack 2 .locals init ( [0] int32 Add1) L_0000: nop L_0001: ldarg.0 L_0002: ldc.i4.1 L_0003: add.ovf L_0004: starg.s x L_0006: ldarg.0 L_0007: stloc.0 L_0008: br.s L_000a L_000a: ldloc.0 L_000b: ret }
PlusEqual2和Add2的IL几乎相同:
.method public static int32 Add2(int32 x) cil managed { .maxstack 2 .locals init ( [0] int32 Add2) L_0000: nop L_0001: ldarg.0 L_0002: ldc.i4.2 L_0003: add.ovf L_0004: starg.s x L_0006: ldarg.0 L_0007: stloc.0 L_0008: br.s L_000a L_000a: ldloc.0 L_000b: ret }