Re: Deep thoughts on .ToArray()
- From: Göran Andersson <guffa@xxxxxxxxx>
- Date: Wed, 07 Jan 2009 03:59:47 +0100
RayLopez99 wrote:
Now that I've learned about 90% of whatever there is to learn about C#
in about six months time,
Give it another six months, and you will realise that then you have really learned about 50%. ;)
I'm going back and looking at some old
programs I wrote my first month, and seeing where I can improve
efficiency.
One (bad? that's the question) habit I picked up the first month of
coding in C# is found below. My question: is this really a bad habit
or a safe "belt and suspenders" approach?
// here it is:
int[] AnIntegerArray;
int[] ASecondArrayOfInts = new int[2]{1,2};
int Length1 = ASecondArrayOfInts.Length; //needed?
No, it's not needed. You don't need to store the value of the property in a variable to use it.
AnIntegerArray = new int[Length1]; //needed?
Definitely not. You are creating an array that is just thrown away when the reference is replaced with another array in the next line.
AnIntegerArray = ASecondArrayOfInts.ToArray();
// can the above few lines - "needed?" - be eliminated (deleted) as
they are already included in:
AnIntegerArray = ASecondArrayOfInts.ToArray(); //?
// I am looking to make a shallow copy of the ASecondArrayOfInts,
which I think is automatically done with .ToArray() (which uses
implicitly 'new'), right?
Using ToArray on an array is only possible when targeting framework 3.5 where the IEnumerable interface (which the Array class implements) has that extension method.
The ToArray method creates a Buffer object from the IEnumerable (the array in this case). This normally means that the items in the collections are enumerated and added to an internal array one at a time, expanding the target array when needed. Then the buffer would create yet another array and copy the items to it and return as result. However, in the special case when the IEnumerable object also implements ICollection (which the Array class does), it can use the CopyTo method to copy the data to the new array without having to enumerate all the items. So, the items will only be copied once in this case.
Still, there is a bit of overhead when calling the ToArray method compared with calling the Array.CopyTo method yourself. Also, it's not so obvious that the ToArray method actually creates a shallow copy. For an array the ToArray method could just have returned the array object itself, just as the ToString method of the String class just returns the string object itself.
--
Göran Andersson
_____
http://www.guffa.com
.
- Follow-Ups:
- Re: Deep thoughts on .ToArray()
- From: RayLopez99
- Re: Deep thoughts on .ToArray()
- References:
- Deep thoughts on .ToArray()
- From: RayLopez99
- Deep thoughts on .ToArray()
- Prev by Date: Re: C# forms
- Next by Date: RE: I couldn't see what the method would do
- Previous by thread: Re: Deep thoughts on .ToArray()
- Next by thread: Re: Deep thoughts on .ToArray()
- Index(es):
Relevant Pages
|