有没有如果使用一个对象初始化,或者是asthetic的性能改进? [英] Is there a performance improvement if using an object initializer, or is it asthetic?
问题描述
因此,比较会之间:
MyClass foo = new MyClass();
foo.Property1 = 4;
foo.Property2 = "garfield";
和
MyClass foo = new MyClass { Property1 = 4, Property2 = "garfield" };
它是语法糖,或者是有实际一些性能增益(不过分钟,它很可能是?)
Is it syntactic sugar, or is there actually some kind of performance gain (however minute it's likely to be?)
推荐答案
它实际上有可能的非常的稍慢使用对象初始化,而不是调用一个构造函数,然后分配的属性,因为它有一个额外的任务:
It's actually potentially very, very slightly slower to use an object initializer than to call a constructor and then assign the properties, as it has one extra assignment:
MyClass foo = new MyClass();
foo.Property1 = 4;
foo.Property2 = "garfield";
VS
vs
MyClass tmp = new MyClass();
tmp.Property1 = 4;
tmp.Property2 = "garfield";
MyClass foo = tmp;
之前参考被分配给变量的属性都被分配。这种差异是一个的可见的之一,如果它的重用一个变量:
The properties are all assigned before the reference is assigned to the variable. This difference is a visible one if it's reusing a variable:
using System;
public class Test
{
static Test shared;
string First { get; set; }
string Second
{
set
{
Console.WriteLine("Setting second. shared.First={0}",
shared == null ? "n/a" : shared.First);
}
}
static void Main()
{
shared = new Test { First = "First 1", Second = "Second 1" };
shared = new Test { First = "First 2", Second = "Second 2" };
}
}
输出显示,在第二行主要
,当二
正在设置(后首先
)中, shared.First
的值仍然是第一 - 即共享
尚未分配的新的价值呢。
The output shows that in the second line of Main
, when Second
is being set (after First
), the value of shared.First
is still "First 1" - i.e. shared
hasn't been assigned the new value yet.
正如马克说,虽然,你几乎可以肯定从来没有真正发现一个差异。
As Marc says though, you'll almost certainly never actually spot a difference.
匿名类型有保证使用构造函数 - 的形式在C#3语言规范的第7.5.10.6给出
Anonymous types are guaranteed to use a constructor - the form is given in section 7.5.10.6 of the C# 3 language specification.
这篇关于有没有如果使用一个对象初始化,或者是asthetic的性能改进?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!