0

I have a list of floats:

List<float> myList = new List<float>(100);

The list works like a shift-left array where the first object in list is removed and a new object is added to the end of the list. Like that:

myList.RemoveAt(0);
myList.Add(sampleFromCollection);

I wondered if using an array (that have a shift left method) instead of a list will be faster?

2
  • Search "circular buffer". Commented Jul 16, 2015 at 16:02
  • 2
    Sounds like you want a queue, not a list. Commented Jul 16, 2015 at 16:02

2 Answers 2

2

You should use Queue instead of List. Use the Enqueue method to add to the list and Dequeue to pop one off the front. For example:

Queue<string> numbers = new Queue<string>();
numbers.Enqueue("one");
numbers.Enqueue("two");
numbers.Enqueue("three");
numbers.Enqueue("four");
numbers.Enqueue("five");

while(numbers.Count > 0)
{
    string value = numbers.Dequeue();
    //Do something with the value
}
Sign up to request clarification or add additional context in comments.

4 Comments

Queue is more efficient or it is just nicer way to implement it?
The queue is specifically designed for first-in, first out. The link I included in the answer should give more info.
Is there any way to initialize the Queue with a constant number of cells? I have to pass this Queue to a method which need 100 cells in order to make the calculations
The Queue class has a constructor that takes an int specifying the initial size of the Queue. It can still grow beyond that size if you keep putting items in & don't take them out.
2

You understand that the underlying representation of List is an array, right? It doesn't have to be, but it is so that random access is constant time and the cost of adding is amortized by growing the array in chunks.

This means that removing from the "head" is going to be exactly the same cost as with an array as the same amount of work needs to be done.

Adding after a remove will be constant time since it's guaranteed that there will be space for the item that you're adding.

If you really need to have fast remove at either end and fast add at either end, but can live without constant time random access, you probably want to use a deque. If you're removing from the front and adding to the back, use a Queue which will be constant time for either remove or add.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.