ArrayList vs. Vectors in Java if thread safety isn't a concern
Is there really that much of a difference between the performance of Vector
and ArrayList
? Is it good practice to use ArrayLists at all times when thread safety isn't an issue?
Vector originates back from the pre-Collections API days, and have been retrofitted since to be a part of it. From what I've read, the reason it is not deprecated is because the core API depends on it.
ArrayList was written from scratch as a part of the Collections API and as such should be used unless you need to support Java versions down to 1.2.
If you need a thread-safe ArrayList, you can use the static factory method Collections.synchronizedList(new ArrayList<type>);
to generate your list.
If thread safety is not an issue, ArrayList
will be faster as it does not have to synchronize. Although, you should always declare your variable as a List
so that the implementation can be changed later as needed.
I prefer to handle my synchronization explicitly because a lot of operations require multiple calls. For example:
if (!myList.isEmpty()) {
myList.get(0);
}
should be:
synchronized (myList) {
if (!myList.isEmpty()) {
myList.get(0);
}
}
If thread safety isn't an issue you should always use ArrayList
. Vector has the overhead of synchronization and it has been shown that the performance differences between ArrayList
and Vector
are abysmal. You can google for a lot of performance benchmarks.
Here's one Timing & Performance.