C # Increasing an array by one element at the end

In my program, I have a bunch of growing arrays where a new element grows one by one to the end of the array. I defined lists as bottlenecks for speed in a critical state of my program due to their slow access time compared to an array - switching to an array significantly increased performance to an acceptable level. Therefore, to grow an array, I use Array.Resize. This works well, since my implementation limits the size of the array to about 20 elements, so O (N) Array.Resize's performance is limited.

But it would be better if there was a way to simply increase the array with one element at the end without using Array.Resize; which, I suppose, copies the old array to an array of a new size.

So my question is: is there a more efficient method of adding one element to the end of an array without using List or Array.Resize?

+3
source share
7 answers

A Listhas constant time access, like an array. For "growing arrays" you really should use List.

When you know that you can add elements to an array-supported structure, you do not want to add one new size at a time. It is usually best to grow an array by doubling its size when it is full.

+10
source

, List<T> - , . , , :

List<int> values = new List<int>(5);

values.Add(1);
values.Add(2);
values.Add(3);
values.Add(4);
values.Add(5);
+3

, - Array.Resize .

, 20 ( , ), , , ? , .

+2

4 ( ), 4 .

Array? 4 , , , 4 .

+1

AFAIK , , . , , List...?

0

(, 10) , , . , , , Array.Resize

0

I think that every method that wants to use an array will never be optimized because the array is a static structure, so I think it's better to use dynamic structures like List or others.

0
source

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


All Articles