ArrayList vs. Vectors in Java if thread safety isn't a concern

后端 未结 5 2060
遇见更好的自我
遇见更好的自我 2020-12-01 03:52

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

5条回答
  •  不思量自难忘°
    2020-12-01 04:31

    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);
       }
    }
    

提交回复
热议问题