Recently I've implemented a Circular buffer, or circular array, in my script. I was wondering if my implementation using queue would run more efficiently than just extending the List class as described in this article: http://www.blackwasp.co.uk/CircularBuffer.aspx Below is my code: Code (csharp): public class CircularBuffer<T> { Queue<T> _queue; int _size; public CircularBuffer(int size) { _queue = new Queue<T>(size); _size = size; } public void Add(T obj) { if (_queue.Count == _size) { _queue.Dequeue(); _queue.Enqueue(obj); } else _queue.Enqueue(obj); } public T Read() { return _queue.Dequeue(); } public T Peek() { return _queue.Peek(); } } I am going to test both methods myself now, but figured I'd ask on the forums first to see if anyone has already encountered this circumstance before.
looks like my method is about 43% more efficient in unity 3d . I ran 100 tests and avg'd the ms of each method. the tests included loading up the array, peeking, and releasing all the data up to 1 million ints. quick n dirty.
Hey Nevulus thanks so much for this. I was wondering if you could take a look at my code and tell me if I'm using it correctly. I'm kinda new to C#, and I'm not sure if it makes sense: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; // required for dealing with audiomixers [RequireComponent (typeof(AudioSource))] public class MicrophoneOn : MonoBehaviour { void Start (){ AudioSource audio = GetComponent<AudioSource>(); audio.clip = Microphone.Start("Built-in Microphone", true, 100, 44100); audio.loop = true; CircularBuffer<float> Buffer = new CircularBuffer<float> (1024); //Getting Sample Data from Microphone float[] samples = new float[audio.clip.samples * audio.clip.channels]; audio.clip.GetData(samples, 0); int i = 0; float sample = 0; float Sample = 0; //Setting each value in the array and adding them to the Circular Buffer //Reading the next Sample from the Circular Buffer while (i < samples.Length) { samples [i] = sample; Buffer.Add (sample); Sample = Buffer.Peek(); ++i; } float newsample = 0; //Deriving the new sample value foreach (float _sample in samples) { newsample = (sample * Sample); } //Putting the new sample values in different array float[] newsamples = new float[audio.clip.samples * audio.clip.channels]; for (int r=0; r < samples.Length; ++r) { newsamples [r] = newsample; } //Setting new sample value to be read by DAC audio.clip.SetData(newsamples, 0); audio.Play(); } }