Skip to content

CircularBuffer

Matheus Lessa Rodrigues edited this page Oct 28, 2017 · 1 revision

CircularBuffer

A collection that resembles a queue with fixed capacity. New elements are added to the end and, if it would overflow its capacity, the CircularBuffer discards the first element. It does not support removal, though.

This collection is particularly useful when you need to hold a certain number of elements but also needs to be constantly be removing old values and adding new ones.

An example of this use case is when you need to store object positions received from the game server. These positions are stored based on an interpolation delay and only the new ones are relevant.

Example

using UnityEngine;
using BitStrap;

public sealed class MyScript : MonoBehaviour
{
    private CircularBuffer<int> myBuffer = new CircularBuffer<int>( 3 ); // Can store up to 3 elements

    private void Start()
    {
        myBuffer.Add( 100 );
        myBuffer.Add( 200 );
        myBuffer.Add( 300 ); // Reaches maximum capacity

        Debug.Log( myBuffer[0] ); // Prints "100"

        myBuffer.Add( 400 ); // Adds 400, drops 100

        Debug.Log( myBuffer[0] ); // Prints "200"

        foreach( var element in myBuffer )
            Debug.Log( element );
        // Prints 200 300 400
    }
}
Clone this wiki locally