开发者

Declaring collections in C#

My question is: What is the most efficient and correct, for large set of data ?

 _pointBuffer1 = new Point3DCollection {  
            new Point3D(140.961, 142.064, 109.300), new Point3D(142.728, 255.678, (...)

-- or --

_pointBuffer1.Add(new Point3D(140.961, 142.064, 109.300)); 开发者_运维问答_poitBuffer1.Add(142.728, (...)

Or is it the same ?

Point3D is declared as a Point3DCollection, but my question is for any object collection (could be Int32 for example) ..


I would strongly suggest using the collection initializer for the sake of clarity (although I'd use some newlines as well).

They don't quite end up as the same IL, mind you. The first ends up being equivalent to:

var tmp = new Point3DCollection();
tmp.Add(new Point3D(140.961, 142.064, 109.300));
tmp.Add(new Point3D(142.728, 255.678));
...
_pointBuffer1 = tmp;

In other words, the assignment to the eventual variable is only made after all the Add calls.

This is important if your Point3D constructor somehow references _pointBuffer1!


Both are compiled to the same IL. Collection initializers are just syntactic sugar. They will call the Add method. Example:

var res = new List<int>() { 1, 2, 3 };

is compiled to:

List<int> <>g__initLocal0 = new List<int>();
<>g__initLocal0.Add(1);
<>g__initLocal0.Add(2);
<>g__initLocal0.Add(3);
List<int> res = <>g__initLocal0;

The only difference is an additional local variable being declared.


Collection initialisation is syntactic sugar. By this I mean that it is a convenient shorthand that is understood by the complier. The compiler will produce code that is logically identical to calling the collection's add method for each element.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜