c# - Allocation of value types -
when assign instance of value type instance, object copied bit-by-bit target location:
private struct word { public word(char c) { ... } } public void method(word a) { word b = a; //a copied , stored in b }
but given following code:
private word _word; public void method() { _word = new word('x'); }
i suspect right-hand side (rhs) expression evaluated first - instantiates value type on stack - , then value copied , stored on location of _word
field, on heap.
the alternative take left-hand side consideration, , instantiate value type directly on _word
, avoiding having copy object.
is suspicion correct? if is, suppose it's safe assume first block of code perform better second.
//1 instantiation + 10k copies word[] words = new word[10000]; word word = new word('x'); (int = 0; < 10000; i++) words[i] = word; //10k instantiations + 10k copies word[] words = new word[10000]; (int = 0; < 10000; i++) words[i] = new word('x');
note: i'm not trying micro-optimize anything.
edit: core of question is, lee puts it: structs allocated in place directly, or need allocated copied?
when assign instance of value type instance, object copied bit-by-bit target location
when assign instance of value type variable of same type, value copied target location, yes. true of reference types well: reference copied bit bit target location. referent of course stays right is.
i suspect right-hand side (rhs) expression evaluated first
the specification states left hand side evaluted produce variable, right hand side evaluated produce value, , assignment happens.
in examples give evaluation of left hand side not produce observable side effect , therefore evaluation can re-ordered optimizers in c# compiler, jitter or cpu if of them choose. if had like
x[i++] = v();
then side effect on left hand side has happen before call on right hand side.
the core of question is: structs allocated in place directly, or need allocated copied?
the specification states structures allocated in temporary location -- typically stack or register in practice -- , copied final destination. however, there situations in optimizer can determine impossible user notice if mutation happens "in place" @ final destination. copy elision optimization, , c# compiler perform optimization if feels can away it.
for more details see article on subject:
http://ericlippert.com/2010/10/11/debunking-another-myth-about-value-types/
Comments
Post a Comment