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?
To add an element to the specific index there is no method available in Array object. But we can use already available splice method in Array object to achieve this. An array starts from index 0 ,So if we want to add an element as first element of the array , then the index of the element is 0 .
The computational complexity of inserting an element in the middle of an array is O(N), where N is the number of elements in the array. The elements in the array must all be shifted up one index after the insertion, or all the elements must be copied to a new array big enough to hold the inserted element.
I think you can save some time with
var newArray = new myObj[oldArray.Length + 1];
oldArray.CopyTo(newArray, 1);
newArray[0] = InsertRecord(myParam);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With