开发者

Object initializer. Is it quicker than the old method? [duplicate]

This question already has answers here: .NET object creation, whats faster? (4 answers) Closed 9 years ago.

Which is quicker and why?

Person person = new Person();
person.FirstName = "Scott";
person.LastName = "Guthrie";
person.Age = 32;

of...

Person开发者_开发技巧 person = new Person { FirstName="Scott", LastName="Guthrie", Age=32 };


This is absolutely the wrong question to be asking*. You should be asking, 'which of the following is more readable?' This sort of micro-benchmarking leads to really obscure and hard to maintain code (although maybe not in this particular situation).

  • The exception is a situation where you've profiled your code and found that this construct occurs in a very hot code path. However, if you had done that, you also would have benchmarked the two methods and found out the answer for yourself :-).


AFAIK, the latter is syntactic sugar for the former. There should be no difference.


The collection initializer notation will be "expanded" to the first notation at compile time so there should be no runtime costs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜