Search code examples
c#arrayslistprocessing-efficiency

Shift Array left or work with add/remove from List?


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?


Solution

  • 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
    }