Object initializer. Is it quicker than the old method? [duplicate]
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.
精彩评论