Java Vector trimToSize() Method
trimToSize()is, in Java,Vectora utility method provided by the class, used to optimizeVectorthe memory usage of. This method willVectoradjust the capacity (capacity) to the current actual number of stored elements (size), thereby reducing unnecessary memory usage.
Method Syntax
public void trimToSize()
Containing Class
java.util.Vector
Method Purpose
VectorThe class internally uses an array to store elements. WhenVectoradding elements, if the current array is full,Vectorit will automatically expand (usually to 1.5 or 2 times the current capacity). Although this mechanism improves the efficiency of adding elements, it may also cause memory waste.
trimToSize()The method's purpose is toVectoradjust the internal array size to just enough to hold all current elements, releasing extra memory space.
Use Cases
- When
VectorWhen a large number of elements have been added and then some elements have been removed, causing the capacity to be much larger than the actual number of elements - In memory-sensitive applications, when memory usage needs to be optimized
- When it is determined that
Vectorthe content no longer changes, and you want to save memory
Method Implementation Principle
Source Code Analysis
The following isVectorin the classtrimToSize()implementation of the method:
Example
modCount++;
int oldCapacity = elementData.length;
if (elementCount < oldCapacity) {
elementData = Arrays.copyOf(elementData, elementCount);
}
}
Implementation Steps
- Increment the modification counter
modCount(used for fail-fast mechanism) - Get the capacity of the current internal array
oldCapacity - If the current number of elements
elementCountis less than the array capacity:- Use
Arrays.copyOf()to create a new array, the size iselementCount - Copy the original array contents to the new array
- will
elementDataPoint the reference to the new array
- Use
Notes
- This method is synchronized (
synchronized), thread-safe - After calling this method, if new elements are added again,
Vectorit will still automatically expand - For large
Vector, this operation may incur some performance overhead
Usage Examples
Basic Usage
Example
public class VectorTrimToSizeExample {
public static void main(String[] args) {
// Create a Vector with an initial capacity of 10
Vector<String> vector = new Vector<>(10);
// Add 5 elements
for (int i = 0; i < 5; i++) {
vector.add("Item " + (i + 1));
}
System.out.println("Size: " + vector.size()); // Output: 5
System.out.println("Capacity: " + vector.capacity()); // Output: 10
// Call trimToSize()
vector.trimToSize();
System.out.println("Capacity after trim: " + vector.capacity()); // Output: 5
}
}
Practical Application Scenarios
Example
public class VectorMemoryOptimization {
public static void main(String[] args) {
// Simulate a scenario of processing large amounts of data
Vector<Integer> data = new Vector<>(10000);
// Add a large amount of data
for (int i = 0; i < 8000; i++) {
data.add(i);
}
// After processing the data, delete half
for (int i = 0; i < 4000; i++) {
data.remove(0);
}
System.out.println("Before trim - Size: " + data.size() +
", Capacity: " + data.capacity());
// Output: Before trim - Size: 4000, Capacity: 10000
// Optimize memory usage
data.trimToSize();
System.out.println("After trim - Size: " + data.size() +
", Capacity: " + data.capacity());
// Output: After trim - Size: 4000, Capacity: 4000
}
}
Performance Considerations
Time Complexity
trimToSize()The time complexity of the method is O(n), where n isVectorthe number of elements in it. Because it needs to copy the original array to the new array.
Space Complexity
This method creates a new array, so it temporarily uses extra memory space, but eventually releases the excess memory.
Usage Recommendations
- Do not call frequently
trimToSize(), especially in loops - When it is determined that
Vectorthe content basically no longer changes, call it - For small
Vector, the optimization effect is not obvious and can be ignored
Comparison with Other Methods
Comparison with ArrayList's trimToSize()
ArrayListalso hastrimToSize()method, the implementation principle is similar, butArrayListits method is not synchronized.
Comparison with ensureCapacity()
| Method | Purpose | Parameters | Thread Safety |
|---|---|---|---|
trimToSize() |
Shrink capacity to current size | None | Yes |
ensureCapacity(int minCapacity) |
Ensure minimum capacity | Minimum capacity value | Yes |
Summary
Vector.trimToSize()is a practical memory optimization method, especially suitable for the following scenarios:
VectorAfter undergoing a large number of add and remove operations- Environments with limited memory resources
VectorWhen the content is determined to no longer change
When using it, note the following:
- This method creates a new array and copies elements, which has some performance overhead.
- If elements are added again after calling,
Vectorit will still automatically expand - For small
Vectoror frequently changingVector, may not need to use it
Reasonable usetrimToSize()can help optimize the memory usage efficiency of Java programs.
Java Vector