개발그래머
리스트 합치기 list.addAll() vs Collections.addAll() 본문
예제 1
List<Integer> mergedList = new ArrayList<>();
mergedList.addAll(Arrays.asList(1, 2, 3, 4, 5));
실행
1. Arrays.asList(1, 2, 3, 4, 5)에서 Integer []를 생성
2. Arrays.asList 는 List<Integer>를 뒤에서 다시 생성
3. addAll 메서드에서 반복하여 Iterator<Integer>를 이용해 List<Integer> mergedList를 생성
예제 2
List<Integer> mergedList = new ArrayList<>();
Collections.addAll(mergedList, 1, 2, 3, 4, 5);
실행
1. element(1, 2, 3, 4, 5)에서 Integer[]를 생성
2. addAll 메서드에서 반복하여 List<Integer> mergedList를 생성(Interable 대신에)
분석
- 이렇게 보면 예제 2가 더 빨라보임
- Arrays.asList()가 스킵되고 중간 List가 생성되지 않음
- 요소가 배열로 제공되기 때문에 요소를 반복하는 것이 Iterator를 사용하는 것보다 빠를 수 있음
- 프로파일링에 달리 표시되지 않는 한 그 차이는 "중요"할 가능성이 없음
- 조기에 최적화 X
- Java Collection Framework 클래스는 배열보다 느릴 수 있지만 대부분의 응용 프로그램에서 적절하게 수행됨
요약
- 배열에서 요소를 추가하는 경우 -> Collections.addAll(mergedList, arr)
- arr 요소들 또한 배열을 사용하고 있는지 기억하기
- Collection에서 요소를 추가하는 경우 -> mergedList.addAll(otherList)
- 절대 이렇게는 사용 X -> Collections.addAll(mergedList, otherList.toArray())
- 오히려 더 느리게 사용됨
- 어느 쪽이 다른 쪽보다 더 빠르다는 게 아니라 현재 상황에서 불필요한 단계를 건너뛰는 것
Why is Collections.addAll supposed to be faster than c.addAll
The Java API docs say the following about Collections.addAll The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run
stackoverflow.com
코드 리팩토링 전
List<RestaurantSearchResponse> mergedList = new ArrayList<>();
Collections.addAll(mergedList, communityList.toArray(new RestaurantSearchResponse[0]));
Collections.addAll(mergedList, notCommunityList.toArray(new RestaurantSearchResponse[0]));
Collections.addAll(mergedList, pickRestaurantList.toArray(new RestaurantSearchResponse[0]));
코드 리팩토링 후
List<RestaurantSearchResponse> mergedList = new ArrayList<>();
mergedList.addAll(communityList);
mergedList.addAll(notCommunityList);
mergedList.addAll(pickRestaurantList);
결론
- 블로그에서 누군가가 Collections.addAll이 더 성능이 좋다는 말을 보고 초기에 구성
- 중요한 것은 불필요한 스텝을 건너뛰는 것
- 전의 코드는 List 객체를 다시 Array로 바꾼 다음 다시 mergedList에 등록하게 됨
- 후의 코드는 mergedList 객체에 List객체를 바로 등록 -> Array로 바꾸는 부분 스킵 -> 성능 최적화
'Java' 카테고리의 다른 글
[자바스터디 3주차] 연산자 (0) | 2023.05.13 |
---|---|
[자바스터디 2주차] 자바 데이터 타입, 변수 그리고 배열 (0) | 2023.05.06 |
[자바스터디 1주차] JVM은 무엇이며 자바 코드는 어떻게 실행하는 것인가 (0) | 2023.04.24 |
Design Pattern[2] 프록시 패턴 (1) | 2023.04.20 |
Design Pattern[1] 싱글톤 패턴 (0) | 2023.04.19 |