Java Vector trimToSize() Method
trimToSize() is a method in Java's Vector A practical method provided by the class, used to optimize Vector 's memory usage. This method adjusts the Vector 's capacity to the number of elements actually stored (size), thereby reducing unnecessary memory usage.
Method Syntax
public void trimToSize()
Class
java.util.Vector
Method Effect
Vector The class internally uses an array to store elements. When adding to the Vector , if the current array is full, theVector automatically expands (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 job is to adjust the Vector 's internal array size to exactly hold all current elements, releasing excess memory space.
Use Cases
- When
VectorAfter adding a large number of elements and then deleting some, causing the capacity to be much larger than the actual number of elements - In memory-sensitive applications where memory usage needs to be optimized
- OK
VectorWhen the contents no longer change and you want to save memory
Method implementation principle
Source Code Analysis
The following are Vector In the class trimToSize() The method's implementation:
Example
public
synchronized
void
trimToSize
(
)
{
modCount
++;
int
oldCapacity
=
elementData.
length
;
if
(
elementCount
<
oldCapacity
)
{
elementData
=
Arrays.
copyOf
(
elementData, elementCount
)
;
}
}
Implementation Steps
- Increments the modification counter
modCount(used for the fail-fast mechanism) - Gets the capacity of the current internal array
oldCapacity - If the current number of elements
elementCountis less than the array capacity:
Arrays.copyOf() Creates a new array with a size of elementCountelementData Points the reference to the new arrayNotes
- This method is synchronized (
synchronized), thread-safe - After calling this method, if new elements are added again,
Vectorwill still automatically expand - For large
Vector; this operation may incur some performance overhead
Usage examples
Basic Usage
Example
import
java.util.Vector
;
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
import
java.util.Vector
;
public
class
VectorMemoryOptimization
{
public
static
void
main
(
String
[
]
args
)
{
// Simulate a scenario that processes a large amount of data
Vector
<
Integer
data
=
new
Vector
<>
(
10000
);
// Add a large amount of data
for
(
int
i
=
0
;
i
<
8000
;
i
++
)
{
data.
add
(
i
)
;
}
// Delete half after processing the data
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 method's time complexity is O(n), where n is the Vector number of elements in the. This is because it needs to copy the original array into a new array.
Space complexity
This method creates a new array, so it temporarily uses extra memory space, but eventually releases the excess memory.
Usage recommendation
- Do not call frequently
trimToSize(), especially in loops - When you are sure the
Vectorcontents will essentially no longer change, call it - For small
Vector, the optimization effect is not obvious and can be ignored
Comparison with Other Methods
Comparison with ArrayList's trimToSize()
ArrayList also has trimToSize() method; the implementation principle is similar, but ArrayList 's method is not synchronized.
Comparison with ensureCapacity()
| Method | Purpose | Parameters | Thread Safety |
|---|---|---|---|
trimToSize() |
Shrinks the capacity to the current size | None | Is |
ensureCapacity(int minCapacity) |
Ensures a minimum capacity | Minimum capacity value | Is |
Summary
Vector.trimToSize() is a practical memory optimization method, especially suitable for the following scenarios:
VectorAfter experiencing a large number of additions and deletions- Environments with limited memory resources
VectorWhen the contents are certain to no longer change
Note the following when using it:
- This method creates a new array and copies elements, incurring some performance overhead
- If elements are added after calling it,
Vectorwill still automatically expand - For small
Vectoror that change frequentlyVector, may not need to use
Proper use of trimToSize() can help optimize the memory usage efficiency of Java programs.
Java Vector