tags:

views:

80

answers:

3

Hello,

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) ..

+3  A: 

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.

Darin Dimitrov
Hm .. I see .. and what is the most correct in code design and documentation ?
jose
Both are correct. It is up to you to decide what makes your code more readable.
Darin Dimitrov
You can choose whatever your personal coding guidelines saying. The only thing i would do, is to write every `new Point3D()` or `buffer.Add()` on a new line, so that you got a complete list in code.
Oliver
Yes, it would be more correct, but I have ~150 points for this model and many many triangle indices (Int32), and texture coords :/ it would be a huge file. and there are other models too
jose
@jose: It sounds like you shouldn't have that data in your source code then. That's what resource files are for...
Jon Skeet
+6  A: 

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!

Jon Skeet
+1 - Anyone that makes a recommendation *for the sake of clarity* deserves an upvote.
Konamiman
+1  A: 

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.

m_arnell
so it is quite just a matter of code design and readability?
jose
I would say that it is clearer to use collection initialisation as your intent is obvious (i.e. you are initialising the collection).
m_arnell