태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.


'vector'에 해당되는 글 1건

  1. 2008/01/28 ArrayList & Vector의 차이점 (1)
2008/01/28 09:36

ArrayList & Vector의 차이점

Vector or ArrayList -- which is better and why?


SometimesVector is better; sometimes ArrayList is better; sometimes you don'twant to use either. I hope you weren't looking for an easy answerbecause the answer depends upon what you are doing. There are fourfactors to consider:

Vector 가 더 나을 때도 있고, ArrayList가 더 나을 때도 있다. 또는, 둘 다 사용하길 원하지 않을 수도 있다. 나는 당신이쉬운 답을 찾으려 하지 않기를 바란다. 왜냐하면 답은 당신이 하는 방식에 따라 달라질 테니까 말이다. 고려해야 할 다음 4가지요인이 있다.

API

In The JavaProgramming Language (Addison-Wesley, June 2000) Ken Arnold, JamesGosling, and David Holmes describe the Vector as an analog to theArrayList. So, from an API perspective, the two classes are verysimilar. However, there are still some major differences between thetwo classes.

TheJava Programming Language 에 Ken Arnold, James Gosling, and DavidHolmes는 Vector를 ArrayList의 상사형(서로 형이 같은)이라고 묘사한다. 그래서 API를 보면 두 개의 클래스는매우 유사하다. 하지만 여전히 두 클래스 사이에는 중요한 차이점이 존재한다.

Synchronization

Vectorsare synchronized. Any method that touches the Vector's contents isthread safe. ArrayList, on the other hand, is unsynchronized, makingthem, therefore, not thread safe. With that difference in mind, usingsynchronization will incur a performance hit. So if you don't need athread-safe collection, use the ArrayList. Why pay the price ofsynchronization unnecessarily?

Vector 는 동기화 되어있다. Vector의 내용에 접근하는 어떤 메소드는 thread safe1 하다. 반면에ArrayList는 동기화되어있지 않다. 그러므로 ArrayList로 만들어진 것은 thread safe하지 않다. thread safe가 필요하지않는데도 동기화를 사용하면, performance hit2 을 초래할 것이다. 만약 당신이 thread-safe 컬렉션을 필요로하지 않는다면, ArrayList를 사용하라. 왜 불필요하게 synchronization의 비용을 지불하려 하는가?

Data growth

Internally,both the ArrayList and Vector hold onto their contents using an Array.You need to keep this fact in mind while using either in your programs.When you insert an element into an ArrayList or a Vector, the objectwill need to expand its internal array if it runs out of room. A Vectordefaults to doubling the size of its array, while the ArrayListincreases its array size by 50 percent. Depending on how you use theseclasses, you could end up taking a large performance hit while addingnew elements. It's always best to set the object's initial capacity tothe largest capacity that your program will need. By carefully settingthe capacity, you can avoid paying the penalty needed to resize theinternal array later. If you don't know how much data you'll have, butyou do know the rate at which it grows, Vector does possess a slightadvantage since you can set the increment value.

내 부적으로 ArrayList와 Vector둘 다 Array를 사용하면서 그들의 컨텐츠를 유지한다. 당신은 당신의 프로그램에서 둘중에 하나를 사용하는 동안에 이 사실을 명심할 필요가 있다. ArrayList 또는 Vector의 요소를 삽입할 때, 만약 그용량을 다 써버린다면, object는 자신의 내부array를 확장시킬 필요가 있다. Vector는 자신의 array 크기의배수만큼 초기화 한다. 반면에 ArrayList는 자신의 array 크기의 50%만큼 씩 증가시킨다. 당신이 이러한 클래스들을사용하는데 의존한다면, 당신은 새로운 요소들을 추가하는 동안에 결국 대량의 performance hit을 초래할 것이다. 당신의프로그램이 필요로 하는 최대의 용량만큼 객체의 초기화 용량을 정하는 것이 최선이다. 신중하게 용량을 셋팅해라. 그러면, 당신은후에 내부 array를 resize하는데 필요한 요금 지불을 피할 있다. 만약 당신이 얼마나 데이터를 가지게 될지는 모른지만,그것이 증가하는 비율을 안다면 , Vector는 당신이 증가값을 정할 수 있기 때문에 근소한 이점을 가진다.(아래 글 참조)

Usage patterns

Boththe ArrayList and Vector are good for retrieving elements from aspecific position in the container or for adding and removing elementsfrom the end of the container. All of these operations can be performedin constant time -- O(1). However, adding and removing elements fromany other position proves more expensive -- linear to be exact: O(n-i),where n is the number of elements and i is the index of the elementadded or removed. These operations are more expensive because you haveto shift all elements at index i and higher over by one element. Sowhat does this all mean?

ArrayList 와 Vector 둘 다 컨테이너의 특정 위치에서 요소들을 되찾거나, 컨테이너의 끝에서 요소들을 더하거나, 삭제할때 유용하다.이러한 모든 기능은 constant time-- O(1)(맨 아래 글을 참조하세요.)에서 수행될 수 있다. 하지만, 어떤 다른자리에서 요소들을 더하거나 제거하는 것은 더 많은 비용을 발생시킨다. 정확하게 직선위에서..-ㅅ-?? n은 요소들의 수이고,i는 더해지거나 제거되는 요소의 인덱스다. 당신이 하나의 요소에 때문에 모든 요소들을 index i에 그 이상의 값으로 옮겨야만하기때문에 이러한 operation들은 더 많은 비용이 든다. 그렇다면 이러한 것은 무엇을 의미하는가?


Itmeans that if you want to index elements or add and remove elements atthe end of the array, use either a Vector or an ArrayList. If you wantto do anything else to the contents, go find yourself another containerclass. For example, the LinkedList can add or remove an element at anyposition in constant time -- O(1). However, indexing an element is abit slower -- O(i) where i is the index of the element. Traversing anArrayList is also easier since you can simply use an index instead ofhaving to create an iterator. The LinkedList also creates an internalobject for each element inserted. So you have to be aware of the extragarbage being created.

그 것은 만약 당신이 요소들을 검색하거나, Array의 끝에서 요소들을 더하거나 제거하기를 원한다면 Vector나 ArrayList둘 중에 하나를 사용하라는 것을 의미한다. 만약 당신이 그 밖의 무엇인가를 하길 원한다면, 스스로 또다른 콘테이너 클래스를찾아라. 예를들어, LikedList는 constant time -- O(1) 에서 어디서든지 요소를 더하거나 제거할 수 있다.하지만, 요소를 찾는 것은 조금 느리다. ArrayList을 왔다갔다 하는 것은 또한 당신이 iterator을 만들어야만 하는대신에 인덱스를 더욱 간편하게 사용할 수 있기 때문에 더 쉽다. LinkedList는 또한 삽인된 각각의 요소에 대한 내부객체를 만든다. 그래서 당신은 만들어지는 여분의 garbage에 대해서 알아야만 한다.

Finally,in "PRAXIS 41" from Practical Java (Addison-Wesley, Feb. 2000) PeterHaggar suggests that you use a plain old array in place of eitherVector or ArrayList -- especially for performance-critical code. Byusing an array you can avoid synchronization, extra method calls, andsuboptimal resizing. You just pay the cost of extra development time.

마 지막으로 Practical Java "PRAXIS 41"에 Peter Haggar은 당신이 Vector 나 ArrayList 둘중의 하나 대신에 명백한 old array를 사용할 것을 제안한다. -특히 비판적인 코드에서??? array를 사용함으로써,당신은 동기화, 여분의 메소드를 부르는 것. 그리고 차선의 resizing을 피할 수 있다. 당신은 단지 여분의 개발시간비용만을지불할 것이다.

Vector - Data Growth 추가사항(API문서)

TheVector class implements a growable array of objects. Like an array, itcontains components that can be accessed using an integer index.However, the size of a Vector can grow or shrink as needed toaccommodate adding and removing items after the Vector has been created.

Vector 클래스는, 오브젝트의 가변장 배열을 구현합니다. 여기에는 배열과 같이, 정수 인덱스를 사용해 액세스 할 수 있는 요소가 격납되고있습니다. 그러나, Vector 의 사이즈는 작성 후에 추가 및 삭제된 객체를 격납할 수 있듯이 필요에 따라서 늘리거나 줄이거나할 수가 있습니다.


Each vector tries to optimizestorage management by maintaining a capacity and a capacityIncrement.The capacity is always at least as large as the vector size; it isusually larger because as components are added to the vector, thevector's storage increases in chunks the size of capacityIncrement. Anapplication can increase the capacity of a vector before inserting alarge number of components; this reduces the amount of incrementalreallocation.

각Vector 는,capacity (용량)와 capacityIncrement (증가량)를 관리하는 것으로써 기억 관리를최적화하려고 합니다.capacity 는 항상 Vector 의 요소수에 가까운 값이며, 통상은 요소수부터 커집니다. 이것은Vector 에 요소가 더해질 때, Vector 의 기억 영역은 capacityIncrement 만 늘려지기 때문입니다. 많은요소를 삽입하기 전에 애플리케이션으로 용량을 필요한 값으로 설정해 두면, 메모리의 재배분의 회수를 줄일 수가 있습니다.



출처 :  http://jania.pe.kr/wiki/jwiki/moin.cgi

1. thread safe : 여러 쓰레드가 어떤 메소드에 동시에 접근해도 정상적으로 작동함. 값의 원치않은 변경등의 문제에서 안전하다.
2. Performance hit : 작업 또는 수행시 타격을 입다.


http://happystory.tistory.com/tag/ArrayList
Trackback 0 Comment 1