x=x+1 vs. x +=1

后端 未结 17 1102
独厮守ぢ
独厮守ぢ 2020-12-29 02:57

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 c

相关标签:
17条回答
  • 2020-12-29 03:27

    They may be the same in VB; they are not necessarily the same in C (where the operator comes from).

    0 讨论(0)
  • 2020-12-29 03:29

    they compile to the same, the second is just easier to type.

    0 讨论(0)
  • 2020-12-29 03:29

    IMPORTANT:

    The answers specifying evaluation are certainly correct in terms of what a += do, in general languages. But in VB.NET, I assume X specified in the OP is a variable or a property.


    They'll probably compile to the same IL.

    UPDATE (to address the probably controversy):

    VB.NET is a specification of a programming language. Any compiler that conforms to what's defined in the spec can be a VB.NET implementation. If you edit the source code of the MS VB.NET compiler to generate crappy code for X += 1 case, you'll still conform to VB.NET spec (because it didn't say anything about how it's going to work. It just says the effect will be exactly the same, which makes it logical to generate the same code, indeed).

    While the compiler is very very likely (and I feel it really does) generate the same code for both, but it's pretty complex piece of software. Heck, you can't even guarantee that a compiler generates the exact same code when the same code is compiled twice!

    What you can feel 100% secure to say (unless you know the source code of the compiler intimately) is that a good compiler should generate the same code, performance-wise, which might or might not be the exact same code.

    0 讨论(0)
  • 2020-12-29 03:30
    1. Yes, they behave the same.
    2. No, they are probably equally efficient. Optimizers are good at that sort of thing. If you'd like to double check, write the optimized code and view it in reflector.
    0 讨论(0)
  • 2020-12-29 03:30

    The optimizer probably produces the same result, if x is a simple type like int or float.

    If you'd use some other language (limited VB knowledge here, can you overload +=?) where x could be one big honking object, the former creates and extra copy, which can be hundreds of megs. The latter does not.

    0 讨论(0)
提交回复
热议问题