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?
Vectors are synchronized. Any method that touches the Vector 's contents is thread safe. ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe.
Performance: ArrayList is faster. Since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe), if one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.
Vector is a thread-safe collection - all its methods are synchronized by default. This is why it's recommended to use ArrayList instead - it's not thread-safe which results in a better performance for single-thread applications.
The members of an ArrayList aren't protected by any memory barriers, so there is no guarantee that changes to them are visible between threads.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With