2011-04-07 6 views
1

다음 방법 중 하나가 성능 적중에서 안전하지 않은 경우 List 크기가 클 것으로 가정합니다 (1,000 개의 개체가있을 수 있음).toArray (new MyObject [size]) 목록 반복 및 배열 채우기

I)

List<String> myList = new ArrayList<String>(); 

for(int i=0; i <=10; i++){ 
    myList.add(""+i); 
} 

String[] array = myList.toArray(new String[myList.size()]); 

myArrayMethod(array); // this method returns the array - it modifies the content but not size of array. 

myListMethod(myList); // this method processes the list. 

II)

List<String> myList = new ArrayList<String>(); 

for(int i=0; i <=10; i++){ 
    myList.add(""+i); 
} 

String[] array = new String[myList.size()]; 
int i = 0; 
for(String str : myList){ 
    array[i] = myList.get(i); 
    i++; 
} 
myArrayMethod(array); // this method returns the array - it modifies the content but not size of array. 

myListMethod(myList); // this method processes the list. 
+2

1,000 항목 크다? 오. – corsiKa

+0

ii30)에서 예를 들어 – smas

+0

@smas에서 foreach를 normal로 바꾸십시오. – dantuch

답변

1

것은 비교적 그들이 그렇게 버전 내장 사용 주어진 동일한 성능 특성을 말하는

String[] array = myList.toArray(new String[myList.size()]); 
3

첫 번째 예제는 System.arraycopy()를 내부적으로 사용할 수 있으므로 약간 더 효율적입니다.

그러나 다른 모든 작업과 비교하여 예를 들어 문자열을 만들면 약간의 차이가 있습니다. 나는 당신이 더 명확하다고 생각하는 것을 제안합니다.

2

컬렉션 코드가 더 좋을 것이라고 생각하기 때문에 제 코드가 1 일 경우 옵션으로 갈 것입니다. 내가 원하는 것보다.

3

toArray()는 읽기 쉽고 빠릅니다.

소스 코드 toArray 메서드를 살펴보면 몇 가지 조건부 및 배열 복사 방법이 있음을 알 수 있습니다.

// ArrayList.class: 
public <T> T[] toArray(T[] a) { 
    if (a.length < size) 
     return (T[]) Arrays.copyOf(elementData, size, a.getClass()); 
    System.arraycopy(elementData, 0, a, 0, size); 
    if (a.length > size) 
     a[size] = null; 
    return a; 
} 

// System.class 
public static native void arraycopy // native method 

arraycopy는 수동으로 추가하는 것보다 큰 배열의 경우 훨씬 빠릅니다.

  • II toArray
  • ) 두 번째 : 추가 수동

    100 000 요소 : 나는, 내가위한 시간을 확인) 그리고 난) 첫 번째 예

    • ) II에 대한 테스트했습니다 ⅰ) 2- MS II) 12 밀리

      1,000,000 요소 : I) 10 밀리 II) 65 밀리