Reputation: 1119
I need to insert a value into an array... ideally I could just start with List<myObj>
, but the methods I need to use return myObj[]
instead.
I always need to insert a value into the first position, and rather than worm the values already in the array... I came up with the following scheme..
List<myObj> list = array.ToList<myObj>();
if (list.Count > 0 && list != null)
{
list.Insert(0, InsertRecord(myParam)); // InsertRecord() is one of my methods...
}
return list.ToArray();
My question is... is this even remotely efficient? Is there a better way to go about doing what I need to accomplish?
Upvotes: 6
Views: 8732
Reputation: 273244
I think you can save some time with
var newArray = new myObj[oldArray.Length + 1];
oldArray.CopyTo(newArray, 1);
newArray[0] = InsertRecord(myParam);
Upvotes: 7
Reputation: 14458
The List<T>
class is backed by an array, so there is no difference in performance between using a List to insert at index 0 and using an array to insert at index 0, except that the BCL developers have tested far more extensively for performance. Don't take the performance hit of the ToList
method and List<T>
constructor, since a new array allocation is happening behind the scenes anyway.
Worse, you might need two array allocations with your posted code, since the List<T>
constructor (called by ToList) may allocate an array of exactly the size of array
, and then the Add
method has to allocate a new array just to perform the insertion. Unlikely, but possible.
In short, allocate the new array yourself.
EDIT:
Given that your method needs to return an array, it doesn't make any sense at all to go through a list. With a list, you are going to copy the original array into the array backing the List<T>
, then insert, then copy that backing array into another array to be returned from your method. That makes two array allocations minimum, plus the possible third that I mentioned above. Using raw arrays guarantees exactly one array allocation.
Upvotes: 3