Value Type Distribution

When you assign an instance of a value type to another instance, the object is copied bit by bit to the target location:

private struct Word
{
    public Word(char c) { ... }
}

public void Method(Word a)
{
    Word b = a; //a is copied and stored in b
}

But given the following code:

private Word _word;

public void Method() {
    _word = new Word('x');
}

I suspect that the right-hand side expression (RHS) is first evaluated, which creates an instance of the value type on the stack, and then the value is copied and stored in the location of the field _wordthat is on the heap.

An alternative would be to take the left side into account and create an instance of the value type directly on _word, avoiding the need to copy the object.

Is my suspicion right? If this is the case, I believe that it is safe to assume that the first block of code will work better than the second.

//1 instantiation + 10k copies
Word[] words = new Word[10000];
Word word = new Word('x');

for (int i = 0; i < 10000; i++)
    words[i] = word;


//10k instantiations + 10k copies
Word[] words = new Word[10000];

for (int i = 0; i < 10000; i++)
    words[i] = new Word('x');

Note. I am not trying to micro-optimize anything.

. , , , ?

+4
3

, .

, , . : . , , , .

, (RHS)

, , , .

, , , #, , , -

x[i++] = v();

.

: ?

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

. :

http://ericlippert.com/2010/10/11/debunking-another-myth-about-value-types/

+9

?

- ?
, ?

(re), , , case WordStruct ctor (no ctor)
struct ctor ,

WordStruct[] WordStructS = new WordStruct[1000];
for (int i = 0; i < WordStructS.Length; i++) { WordStructS[i].C = 'x'; }

, , ,

WordClass[] WordClassS = new WordClass[1000];
for (int i = 0; i < WordClassS.Length; i++) { WordClassS[i] = new WordClass('x'); }

( ), IConable , , ( )
( )

public struct WordStruct : ICloneable 
{
    public char C;
    public WordStruct(char C) 
    {
        this.C = C;
    }
    public object Clone()
    {
        WordStruct newWordStruct = (WordStruct)this.MemberwiseClone();
        return newWordStruct;
    }
}

, ,
, ,


,
?

0

(T).

- .
.

-1

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


All Articles