The ++ operator (int x) creates a new instance each time?

According to MSDN, System.Int32 is immutable, and its members always return new instances. Some common code, such as for a loop, requires c ++ operation quite often. Does increment increase new instances and discard old ones? As far as I can see, this approach will seriously affect performance. And I wonder how Microsoft implements it.

By the way, is increment thread safe? The documentation says that all Int32 elements are thread safe, but there is interlocked.increment ().

Thank.

+3
source share
3 answers

Yes and no.

The answer is yes in the sense that it is:

i++;

equivalent to this:

i = i + 1;

( System.Int32 ):

i = new int(i + 1);

...

.NET , .

. i = i + 1, . .

; , , , : " i++ - - ?" - , .

, :

?

- , . , " ", , . , , , .

, ? , Int32 .,.

, Int32 , . , , , , .

, , i++ - i; i . - i - , , i, 1 . Interlocked.Increment. MSDN ; i .

+3

System.Int32 . , .

. , , . , .

++ , , - .

+1

(++) . MSDN , . .

. , , , , . , , , , .

They say that it x+1is thread safe, because it does not change by itself x(think of it as creating a temporary value). But the purpose x+1- xis not.

The documentation is also technically correct, as ++it is not a member of System.Int32, it is a C # compiler that translates x++to x = x + 1.

0
source

Source: https://habr.com/ru/post/1760946/


All Articles