开发者

meaning of '+='

I开发者_运维问答'm confused with the syntax of C#: what is the use of "+="?


The += syntax can be used in different ways:

SomeEvent += EventHandler;

Adds a handler to an event.


SomeVariable += 3;

Is equivalent to

SomeVariable = SomeVariable + 3;


This is called a compound operator. They are common to all languages I can thing of: Javascript, C, Java, PHP, .net, GL.

Like everyone has said, is a shortened version of value = value + 3.

There are multiple reasons for its use. Most obviously it's quicker to write, easier to read and faster to spot errors with.

Most importantly, a compound operator is specifically designed not to require as much computation as the equivalent value = value + 3. I'm not totally sure why but the evidence is paramount.

Simply create a loop, looping for say 5,000,000 adding a value as you proceed. In two test cases, I know personally from Actionscript, there is roughly a 60% speed increase with compound operators.


You also have the equivalent:

+=: addition

-=: subtraction

/=: multiplication

*=: multplication

%=: modulus

and the less obvious:

++: Plus one

--: Minus one


a += 3

is the same as

a = a + 3


Note, it is not necessarily always equivalent.

for ordinary variables, a+=a is, indeed, equivalent to a=a+a, and shorter!. For the odd variable which changes its state, not so much.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜