Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Increasing an array by one element at the end

In my program I have a bunch of growing arrays where a new element is grown one by one to the end of the array. I identified Lists to be a speed bottleneck in a critical part of my program due to their slow access time in comparison with an array - switching to an array increased performance tremendously to an acceptable level. So to grow the array i'm using Array.Resize. This works well as my implementation restricts the array size to approximately 20 elements, so the O(N) performance of Array.Resize is bounded.

But it would be better if there was a way to just increase an array by one element at the end without having to use Array.Resize; which I believe does a copy of the old array to the newly sized array.

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

like image 568
Projectile Fish Avatar asked Dec 07 '22 04:12

Projectile Fish


2 Answers

A List has constant time access just like an array. For 'growing arrays' you really should be using List.

When you know that you may be adding elements to an array backed structure, you don't want to add one new size at a time. Usually it is best to grow an array by doubling it's size when it fills up.

like image 145
jjnguy Avatar answered Dec 10 '22 03:12

jjnguy


As has been previously mentioned, List<T> is what you are looking for. If you know the initial size of the list, you can supply an initial capacity to the constructor, which will increase your performance for your initial allocations:

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

values.Add(1);
values.Add(2);
values.Add(3);
values.Add(4);
values.Add(5);
like image 43
Richard Szalay Avatar answered Dec 10 '22 03:12

Richard Szalay