.Net 中的复合赋值

Compound Assignment in .Net

我想知道在 .Net 中是否曾经或现在仍然如此。

Use exp += val instead of exp = exp + val. Since exp can be arbitrarily complex, this can result in lots of unnecessary work. This forces the JIT to evaluate both copies of exp, and many times this is not needed. The first statement can be optimized far better than the second, since the JIT can avoid evaluating the exp twice.

这来自 codeproject 中的一篇古老文章。

cpp 中还有一个:

However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation.

是的,它曾经是,现在仍然是 .NET 中的最佳实践。想象一下你要加4到

myObject.MyExpensiveMethod().MyProperty

显然你不想这样做:

myObject.MyExpensiveMethod().MyProperty = 
    myObject.MyExpensiveMethod().MyProperty + 4;

因为它调用了两次昂贵的方法,而 += 只调用了一次。你可以这样做:

var temp = myObject.MyExpensiveMethod();
temp.MyProperty = temp.MyProperty + 4;

较少昂贵,但最便宜:

myObject.MyExpensiveMethod().MyProperty += 4;

因为昂贵的方法只被调用一次。

另一种情况是当你使用一个有副作用但只想调用一次的方法时:

myFactory.GetNextObject().MyProperty += 5;

你_肯定不会

myFactory.GetNextObject().MyProperty = myFactory.GetNextObject().MyProperty + 5;

您可以再次使用临时变量,但复合赋值运算符显然更简洁。

诚然,这些都是极端情况,但养成这种习惯并不是坏习惯。