I recently learned the core .NET Queue
type uses arrays internally, and that this is actually much more efficient. I've had a go at writing a singly-linked list version of a queue, MyQueue
.
Running basic stopwatch times against this type and the .NET type shows about 50ms difference when queuing 1 million items and checking the length.
How can it be improved?
MyQueueNode
namespace MyQ.Core
{
public class MyQueueNode<T> : IMyQueueNode<T>
{
private MyQueueNode<T> _nextNode;
private T _value;
public MyQueueNode(T value)
{
_value = value;
}
public void SetNextNode(ref MyQueueNode<T> nextNode)
{
_nextNode = nextNode;
}
public MyQueueNode<T> GetNextNode()
{
return _nextNode;
}
public T GetValue()
{
return _value;
}
}
}
MyQueue
namespace MyQ.Core
{
public class MyQueue<T> : IMyQueue<T> where T : class
{
private volatile MyQueueNode<T> _headNode, _tailNode;
public void Enqueue(T item)
{
MyQueueNode<T> newNode = new MyQueueNode<T>(item);
if (_headNode == null)
{
_headNode = newNode;
_tailNode = _headNode;
}
else
{
_tailNode.SetNextNode(ref newNode);
_tailNode = newNode;
}
_length++;
}
public T Dequeue()
{
if(_headNode == null)
{
throw new QueueEmptyException();
}
T value = _headNode.GetValue();
_headNode = _headNode.GetNextNode();
_length--;
return value;
}
public T Peek()
{
if(_headNode == null)
{
return null;
}
return _headNode.GetValue();
}
private long _length = 0;
public long Length => _length;
}
}
#region
I've removed them so there's no confusion. \$\endgroup\$