0

I want to develop a program that will constantly calculate an average from 1000 elements (this is not the question). The problem is this:

Something like private double[] collection = new double[1000];.

The program is event driven and there are times new elements have to be put to the array. When a new one is put, the very first is removed, so I have to shuffle all elements which will slow me down.

Is there a ready structure like Queue, which can pop the first element and add a new one at the last position, and a structure that I can read all elements from 0-th to the 1000 element [and speed is of the essence, because there will be times when this a new element will be added 10-20 times a second]?

The highest NET framework I can use is 3.5, so there is no ConcurrentQueue available there. And I want to go through each element upon dequeueing and enqueueing an item, because I need to do some calculations with them.

  • There is none built in that does exactly that, but see [duplicate](http://stackoverflow.com/questions/5852863/fixed-size-queue-which-automatically-dequeues-old-values-upon-new-enques) for a Queue that automatically dequeues older items (which was the first hit for me for the query "C# fixed size queue"). If this is not what you're looking for, please elaborate what you found and why that didn't suffice. – CodeCaster May 26 '15 at 09:27
  • 10-20 times a second is not very fast. Use one of the built-in collections. Maybe even `List`. – John Saunders May 26 '15 at 09:28
  • You do not need a classic Queue for this. I think that CircularBuffer http://en.wikipedia.org/wiki/Circular_buffer is the right structure, easy to implement, fast add/remove from start and end (no need to shift elements), fast iteration... – Dusan May 26 '15 at 09:31
  • 1
    @Dusan as one can read on [MSDN](https://msdn.microsoft.com/en-us/library/35bz1ab7.aspx) or [SO](http://stackoverflow.com/questions/13275975/circularbuffer-highly-efficient-implementation-both-thread-safe-and-not-thread), the .NET Queue is implemented as a circular buffer. – CodeCaster May 26 '15 at 09:35
  • OK, I did not know that. Learn something new every day. – Dusan May 26 '15 at 09:36
  • Forgot to mention I need to use .Net 3.5, no higher version is allowed. – Victor Velchev May 26 '15 at 09:37
  • ConcurrentQueue is required only if you are accessing Queue object from multiple concurrent threads. I think you are not in this situation, so forget about ConcurrentQueue. – Dusan May 26 '15 at 09:43
  • See the example on how to iterate through Queue elements - normal `foreach`: https://msdn.microsoft.com/en-us/library/4a9449ty%28v=vs.110%29.aspx To limit Queue you can use: http://stackoverflow.com/questions/1292/limit-size-of-queuet-in-net – Dusan May 26 '15 at 09:44

0 Answers0