3

In c#, is there any difference (semantics, efficiency, etc.) between writing x = x + 1 and x += 1? Is it compiled to the same thing? Or optimized in some way?

For me, looks like it should be the same or += should be "optimized" as x = x + ..., but is it?

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • https://sharplab.io/#v2:EYLgtghgzgLgpgJwDQxASwDYB8ACAmARgFgAoHAZgAJ9KBhSgb1MpeqpwBZKBZACgEpGzViLQA7GAG0AupQDmlALyNKBAL4BuYSJbadcyQAZZAamUEtJHaz0icBAJy85/SyLV7brCtS4A5ASEra0pxKVkFZQZVTS9dYOsDYyV5I1NVNxD7JxdMlg8SUjUgA= is one example. – mjwills Feb 15 '21 at 12:33
  • @dratenik C# does not allow compound operators to be overloaded, they will just refer to the non-compound version. MSIL allows it, I'm not sure if C# will recognize it though – Charlieface Feb 15 '21 at 12:34
  • @mjwill Interesting, but I'd love to know if there was any practical difference between `ldelema ldind` and `ldelem`, looking at the ASM it's probably only a difference for multithreading, where you should be interlocking anyway – Charlieface Feb 15 '21 at 12:40
  • You'd need to benchmark to be sure @Charlieface. – mjwills Feb 15 '21 at 12:41
  • 6
    Declare x as *byte* and you'll easily notice the difference. One of the less pretty quirks of C#. Otherwise just syntax, IL does not have a += operator so the C# compiler has to use +. – Hans Passant Feb 15 '21 at 13:10
  • Given the duplicate does not appear to cover either of the scenarios mentioned in the comments here, someone may wish to add an answer / comment to the duplicate. – mjwills Feb 15 '21 at 19:53

0 Answers0