x = x + 1与x + = 1 [英] x=x+1 vs. x +=1

查看:163
本文介绍了x = x + 1与x + = 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,这两个命令的结果相同,即将X递增1,但后者可能更有效.

I'm under the impression that these two commands result in the same end, namely incrementing X by 1 but that the latter is probably more efficient.

如果这不正确,请说明差异.

If this is not correct, please explain the diff.

如果正确,为什么后者应该更有效?他们俩不应该编译为相同的IL吗?

If it is correct, why should the latter be more efficient? Shouldn't they both compile to the same IL?

谢谢.

推荐答案

来自适用于+ = 的MSDN库:

使用此运算符几乎与指定result = result + expression相同,只是结果只被评估一次.

Using this operator is almost the same as specifying result = result + expression, except that result is only evaluated once.

所以它们并不相同,这就是为什么x + = 1会更有效.

So they are not identical and that is why x += 1 will be more efficient.

更新:我只是注意到我的MSDN库链接是指向JScript页面的,而不是

Update: I just noticed that my MSDN Library link was to the JScript page instead of the VB page, which does not contain the same quote.

因此,在进一步研究和测试后,该答案不适用于VB.NET.我错了.这是一个示例控制台应用程序:

Therefore upon further research and testing, that answer does not apply to VB.NET. I was wrong. Here is a sample console app:

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

PlusEqual1和Add1的IL确实相同:

IL for both PlusEqual1 and Add1 are indeed identical:

.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也几乎相同:

The IL for PlusEqual2 and Add2 are nearly identical to that as well:

.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 
}

这篇关于x = x + 1与x + = 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆