Stack .TrimExcess Method in C#
In this post, we will explore the TrimExcess method in C# along with its syntax and illustrations.
What is the Stack__PRESERVE_2__.TrimExcess Method?
A stack represents a linear data arrangement that executes actions in a particular order. This order could be either Last In, First Out (LIFO) or First In, Last Out (FILO). LIFO signifies that the most recently added item is the first one to be removed, while FILO indicates that the initial item inserted is the last one to be removed.
In C#, the TrimExcess method belongs to the System.Collections namespace. This particular generic namespace pertains to the Stack<T> class. The purpose of this method is to enhance memory efficiency of a Stack<T> object by resizing the array to match the number of items in the stack if it falls below a specific threshold. The primary objective of utilizing this technique is to reduce the memory usage of the stack after it has been substantially reduced due to a series of push and pop operations.
The Stack<T>.TrimExcess function is employed to establish a threshold on the quantity of items in the Queue<T>, provided it falls below 90% of the current capacity. Unlike a fixed-size data structure, a stack in C# does not have a predetermined capacity. Its size is flexible and determined by available system memory. This approach is commonly utilized for efficient memory handling of large stacks.
Stack Properties:
- The capacity of a Stack refers to the amount of components it can hold. As pieces are added to a Stack, its capacity is dynamically raised as needed via reallocation.
- If the count is fewer than the stack's capacity, Push is an O(1) operation . If the capacity must be expanded to handle the additional element, Push becomes an O(n) operation, where n represents Count. Pop is an O(1) operation.
- Stack accepts null as a valid value and allows element duplication.
Syntax:
It has the following syntax:
public void TrimExcess ();
Key Points To Remember:
- If no new elements are added to the collection, this technique can be used to reduce its memory load.
- In order to return a Stack<T> to its original state, use the Clear method before executing the TrimExcess function.
- Trimming an empty Stack<T> resets its capacity to the default value.
Example:
Let's consider a scenario to demonstrate the Stack<T>TrimExcess function in C#.
using System;
using System.Collections.Generic;
class TrimExcess{
// Driver code
public static void Main()
{
// A string of string datatype is created
Stack<string> mystk = new Stack<string>();
// insertion of elements into the stack
mystk.Push("1st element");
mystk.Push("2nd element");
mystk.Push("3rd element");
mystk.Push("4th element");
mystk.Push("5th element");
// display of elements into teh stack
Console.WriteLine(mystk.Count);
// clearing the elements of the stack
mystk.Clear();
// the TrimExcess method()
mystk.TrimExcess();
// to print the elements of the stack
Console.WriteLine(mystk.Count);
}
}
Output:
Explanation:
In this instance, a Stack named mystk is set up to store string values, and five items are added using the Push operation. Subsequently, the code displays the initial count of items in the stack, clears all elements with the Clear function, and proceeds to optimize the capacity with the TrimExcess function, which is deemed unnecessary.
Finally, the software displays the count of items after the cleaning and trimming processes. It's important to highlight that the TrimExcess function is typically applied to data structures such as List<T> to reduce unnecessary capacity. However, this method doesn't impact a Stack significantly as it doesn't reserve extra memory beyond what is essential for holding its elements.
Advantages of using TrimExcess method
Several advantages of TrimExcess method are as follows:
- Memory efficiency: TrimExcess allows us to trim the collection's internal capacity to match its real size. It is especially useful when the initial capacity was increased to meet future expansion but that development did not occur.
- Optimized Resource allocation: Reducing a collection's capacity might result in a lower memory footprint. It is significant in situations where memory utilization is a crucial concern, particularly in resource-constrained situations.
- Optimized Resource Utilization: Reducing excess capacity reduces memory consumption and maximizes resource efficiency. It is particularly beneficial when memory allocation is constrained.
- Improving Performance: In collections with dynamic resizing, excess capacity can slow down processes like resizing and copying pieces. Excess capacity can be reduced to enhance performance by preventing inefficient reallocations.
- Predictable Resource consumption: The collection's memory consumption becomes more consistent and closely matched to its real content by removing an excess capacity. This predictability can be essential in situations involving critical resource management.
- Improved Workload Modification: When a collection's size varies, TrimExcess' dynamic capacity adjustment makes it possible for the collection to change with workloads more effectively without retaining extra memory.