Introduction
Stack collections store their elements in a different way from queues, which store them in a FIFO manner (First In, First Out). The elements are included in the order in which they were added. Generic Queue and non-generic Queue collections are included in C#. Using the generic queue collection is advised.
Constructors
Constructor |
Description |
Queue() |
Creates a brand-new, empty instance of the Queue class using the default growth factor and initial capacity. |
Queue(Int32) |
Creates a brand-new, empty instance of the Queue class using the default growth factor and has the specified initial capacity. |
Queue(IEnumerable) |
Creates a new instance of the Queue class with the default configuration, the initial capacity equal to the number of elements copied, and elements copied from the supplied collection. |
Here are some key features and operations related to queues in C#.
1. Creating a Queue
The Queue class can be used to establish a queue and describe the kind of elements it will hold. As an illustration, consider this.
Queue<string> queue = new Queue<string>();
If you already have a list or any data, and you want to add that data, then it's also possible to add data to the queue.
var lstElements = new List<string>() { "element 1", "element 2", "element 3" };
Queue<string> queue = new Queue<string>(lstElements);
while (queue.Count > 0)
{
Console.WriteLine(queue.Dequeue());
}
2. Enqueue
To add components to the end of the queue, use the Enqueue method. It adds the element to the queue after accepting it as an argument. As an illustration, consider this.
queue.Enqueue("element 1");
queue.Enqueue("element 2");
3. Dequeue
The element at the front of the queue is removed and retrieved using the Dequeue method. It gives back the deleted part. As an illustration, consider this.
string firstElement = queue.Dequeue();
See here we use the Dequeue method and when we use they can remove that value from the queue itself as well.
4. Peek
The element at the head of the queue is retrieved using the Peek method without being deleted. It does not change the queue; instead, it returns the element. As an illustration, consider this.
string firstElement = queue.Peek();
See here, we are using the Peek method, and when we are using, they can simply print the value of the queue but don’t remove that value from the queue.
5. Count
To find out how many elements are in the queue, utilize the Count property. As an illustration, consider this.
int count = queue.Count;
6. Clear
All elements in the queue are eliminated using the Clear technique. As an illustration, consider this.
queue.Clear();
7. CopyTo
Using the array index as a starting point, this method copies the members of the queue to an already existing one-dimensional array. This technique is O(n) in nature, where n is the count because the elements are transferred to the Array in the same order that the enumerator iterates through the Queue. Under the System. Collections namespace, this method is located.
var lstElements = new string[5];
queue.CopyTo(lstElements, 0);
8. Contains
We use the Contains() method of the queue to determine whether it contains a specific element value. The method returns true when that value is present in the queue. It returns false otherwise. As an illustration, consider this.
queue.Contains(“element 2”);
9. Ensure Capacity
Make sure that this queue has a capacity that is at least the designated capacity. It is upgraded to at least the designated capacity if the present capacity is less than capacity.
queue.EnsureCapacity(2);
Trim Excess
The generic queue class (Queue) in C# is actually implemented as an array in the background. Every now and again C# resizes that array to create room for additional elements. But that array doesn't get smaller as we take elements out of it. That may provide a large amount of idle queue capacity.
We use a queue's TrimExcess() method to reduce its extra capacity. The underlying capacity of the queue is resized in that way to reflect its real amount of entries, but not more. That can cut down on the memory overhead of the queue considerably.
Two key components of the trim excess approach are.
- When the queue length reaches 90% or more of its capacity, the procedure does nothing (Microsoft Docs, n.d.). TrimExcess() won't have to waste time resizing the array when there isn't much space left over in this manner.
- Actual elements are never eliminated from the queue by the procedure. It just clears off the underlying array's unused space. Everything in the queue stays the same.
queue.TrimExcess()
In the above screenshot, we are using the trim excess method to reduce the unused data from the queue. When we use the Dequeue() method at that time, it will peek the data from the queue and remove it from the queue as well, but at that time, it will not reduce the actual size of the queue, so for that, we are using the trim excess method, and it’s reduced the size.
Once we reduce the unused data from the queue, we check the capacity of the queue again using the EnsureCapacity() method, and in that, we provide the capacity value as well. If it does not match the capacity value, it will increase the value as well. In the above screen-show, we checked the ensure capacity as 7, but it didn’t match, so it will be increased by 12 capacity.
It's important to remember that the Queue class offers additional helpful attributes and methods for handling queues.
Pros and Cons of Queue
A data structure that adheres to the First-In-First-Out (FIFO) principle is a queue. It is crucial to weigh the many benefits and drawbacks of it. Below are the benefits and drawbacks of using a queue.
Advantages of Queue
- Efficient data retrieval: Efficient element retrieval is made possible by queues, particularly when obtaining the front element or appending elements to the rear. The temporal complexity of these operations is O(1).
- Order preservation: In order to guarantee that the first element added is the first one withdrawn, queues maintain the order in which elements are introduced. Because of this, queues are appropriate in situations where keeping the order of processes is essential.
- Synchronization: Multiple threads or processes can be synchronized with the usage of queues. They offer a safe and effective means of exchanging data across various software components, guaranteeing that operations are carried out in a regulated and systematic fashion.
- Buffering: When the rate of data creation exceeds the rate of data consumption, queues can function as buffers, enabling the temporary storing of data. This buffering capacity aids in data loss prevention and flow management.
Disadvantages of Queue
- Limited access: There are few entry places for queues. Only elements can be taken out from the front and inserted from the back. A different data structure would be more appropriate if elements in the middle of the queue need to be accessed.
- Fixed-size limitation: Certain queue systems are limited in size, meaning they can only contain a specific number of elements. When the queue fills up, new entries can't be added until certain existing ones are taken out.
- Overhead: Performance and memory overhead are possible with queues. Additional RAM can be needed, depending on the implementation, to hold pointers for queue management or metadata.
It's crucial to remember that the benefits and drawbacks of queues might change based on the particular use case and application needs.