Efficient way to insert a value into an array?

I need to insert a value into an array ... ideally, I could just start with List<myObj> , but instead I need to use return myObj[] .

I always need to insert the value in the first position, and not the value worm 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 it even remotely effective? Is there a better way to do what I need to accomplish?

+4
source share
2 answers

I think you can save time

 var newArray = new myObj[oldArray.Length + 1]; oldArray.CopyTo(newArray, 1); newArray[0] = InsertRecord(myParam); 
+7
source

The List<T> class is supported by the array, so there is no performance difference between using the list to insert at index 0 and using the array to insert at index 0, except that BCL developers tested much more widely for performance. Do not take the performance hit of the ToList method and the List<T> constructor, since in any case, the distribution of the array still occurs behind the scenes.

Worse, you might need two array distributions with your published code, as the List<T> constructor (called by ToList) can allocate an array of exactly the same size as the array , and then the Add method must allocate a new array to perform the insertion. Hardly, but possible.

In short, select the new array yourself.

EDIT:

Given that your method should return an array, there is no point going through a list. With the list, you are going to copy the original array into an array that supports List<T> , then paste and then copy this support array to another array that will be returned from your method. This makes the two distributions of arrays minimal, plus a possible third, which I mentioned above. Using raw arrays guarantees exactly one array distribution.

+3
source

Source: https://habr.com/ru/post/1385993/


All Articles