持续保存数据

时间:2015-02-27 10:17:39

标签: c#

随着时间的推移,我有一个物体在空间中移动,我想每0.5秒保存它的位置(x,y,z),总共10秒。该对象将不断移动,但我只想要它最近的10秒。

我一直在考虑使用数组[20],但这意味着每0.5秒我必须弹出最后一个元素(比如数据[19]),之前推送每一个元素并在数据中添加当前元素[0]。

有更优雅的方法吗?

编辑:性能可能是个问题,因为我会保存很多这些对象的数据。这就是为什么我正在寻找一种聪明的方法来做到这一点。在此先感谢:)

3 个答案:

答案 0 :(得分:3)

如评论中所述,您可以使用Circular Buffer

这是一个示例实现。

/// <summary>
/// A circular buffer with a maximum capacity set at construction time.
/// You can repeatedly add elements to this buffer; once it has reached its capacity
/// the oldest elements in it will be overwritten with the newly added ones.
/// This is how it differs from a queue: Oldest elements will be overwritten when the buffer is full.
/// </summary>
/// <typeparam name="T">The type of the elements stored in the buffer.</typeparam>

[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Calling this CircularBufferCollection would be stupid.")]

public class CircularBuffer<T>: IEnumerable<T>
{
    /// <summary>Constructor.</summary>
    /// <param name="capacity">The maximum capacity of the buffer.</param>

    public CircularBuffer(int capacity)
    {
        Contract.Requires<ArgumentOutOfRangeException>(capacity > 0, "Capacity must be greater than zero.");

        // We will use a buffer with a size one greater than the capacity.
        // The reason for this is to simplify the logic - we can use "front == back" to indicate an empty buffer.

        _buffer = new T[capacity+1];
    }

    /// <summary>The buffer capacity.</summary>

    public int Capacity
    {
        get
        {
            Contract.Ensures(Contract.Result<int>() > 0);
            return _buffer.Length - 1;
        }
    }

    /// <summary>The number of elements currently stored in the buffer.</summary>

    public int Count
    {
        get
        {
            Contract.Ensures(0 <= Contract.Result<int>() && Contract.Result<int>() <= this.Capacity);

            int result = _back - _front;

            if (result < 0)
            {
                result += _buffer.Length;
            }

            return result;
        }
    }

    /// <summary>Is the buffer empty?</summary>

    public bool IsEmpty
    {
        get
        {
            return this.Count == 0;
        }
    }

    /// <summary>Is the buffer full? (i.e. has it reached its capacity?)</summary>

    public bool IsFull
    {
        get
        {
            return nextSlot(_back) == _front;
        }
    }

    /// <summary>Empties the buffer.</summary>

    public void Empty()
    {
        Contract.Ensures(this.IsEmpty);

        _front = _back = 0;
        Array.Clear(_buffer, 0, _buffer.Length); // Destroy any old references so they can be GCed.
    }

    /// <summary>Add an element to the buffer, overwriting the oldest element if the buffer is full.</summary>
    /// <param name="newItem">The element to add.</param>

    public void Add(T newItem)
    {
        _buffer[_back] = newItem;
        _back = nextSlot(_back);

        if (_back == _front) // Buffer is full?
        {
            _front = nextSlot(_front); // Bump the front, overwriting the current front.
            _buffer[_back] = default(T); // Remove the old front value.
        }
    }

    /// <summary>Removes and returns the oldest element from the buffer.</summary>
    /// <returns>The element that was removed from the buffer.</returns>
    /// <exception cref="InvalidOperationException">Thrown if the buffer is empty.</exception>

    public T RemoveOldestElement()
    {
        Contract.Requires<InvalidOperationException>(!this.IsEmpty, "Cannot remove an element from an empty buffer.");

        T result = _buffer[_front];
        _buffer[_front] = default(T); // Zap the front element.
        _front = nextSlot(_front);

        return result;
    }

    /// <summary>
    /// The typesafe enumerator. Elements are returned in oldest to newest order.
    /// This is not threadsafe, so if you are enumerating the buffer while another thread is changing it you will run
    /// into threading problems. Therefore you must use your own locking scheme to avoid the problem.
    /// </summary>

    public IEnumerator<T> GetEnumerator()
    {
        for (int i = _front; i != _back; i = nextSlot(i))
        {
            yield return _buffer[i];
        }
    }

    /// <summary>The non-typesafe enumerator.</summary>

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Implement in terms of the typesafe enumerator.
    }
    /// <summary>Calculates the index of the slot following the specified one, wrapping if necessary.</summary>

    private int nextSlot(int slot)
    {
        return (slot + 1) % _buffer.Length;
    }

    /// <summary>
    /// The index of the element at the front of the buffer. 
    /// If this equals _back, the buffer is empty.
    /// </summary>

    private int _front;

    /// <summary>
    /// The index of the first element BEYOND the last used element of the buffer. 
    /// Therefore this indicates where the next added element will go.
    /// </summary>

    private int _back;

    /// <summary>The underlying buffer. This has a length one greater than the actual capacity.</summary>

    private readonly T[] _buffer;
}

答案 1 :(得分:0)

正如@zerkms所说,你正在寻找循环缓冲区。

您可以使用linked listqueue进行构建。我们的想法是在列表的末尾添加新元素,如果达到最大大小,则删除第一个元素。

您也可以从数组中构建它。我们的想法是为列表的开头和结尾设置两个索引,然后通过循环(使用modulo)来遍历数组。此外,当startIndex == endIndex您不知道您的列表是空还是满时,您将不得不使用布尔值来了解这一点。 wikipedia说了很多。

最后一个通常是首选,因为您将使用相同的位置来存储您的对象。虽然在C#中它只是存储的引用,但它们不会占用太多空间。

Google将为您提供大量实施此功能。

答案 2 :(得分:0)

您可以使用Queue解决此问题。

如果用它来跟踪x个最新事件。每个事件Enqueue()然后Dequeue(),直到Queue包含您要保留的事件数。