当你将值类型的实例分配给另一个实例时,对象会逐位复制到目标位置:
private struct Word
{
public Word(char c) { ... }
}
public void Method(Word a)
{
Word b = a; //a is copied and stored in b
}
但是考虑以下代码:
private Word _word;
public void Method() {
_word = new Word('x');
}
我怀疑右侧表达式会首先被评估 - 这会在堆栈上实例化一个值类型 - 然后将该值复制并存储在堆上的
_word
字段位置。另一种选择是考虑左侧,直接在
_word
上实例化值类型,避免复制对象。我的怀疑是否正确?如果是这样,我认为第一个代码块比第二个代码块性能更好。
//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');
注意:我并不试图微调任何东西。
编辑:我的问题的核心是,正如Lee所说:结构体是直接分配还是需要先分配再复制?