list.clear () vs list = 새 ArrayList(); [복제]
이 질문에는 이미 답변이 있습니다.
ArrayList를 지우는 데 두 가지 옵션 중 어느 것이 더 빠르고 빠르며 그 이유는 무엇입니까?
list.clear()
또는
list = new ArrayList<Integer>();
임의의 시간에 내 ArrayList에서 모든 항목을 지워야하며 앞으로 몇 개의 새 항목이 있는지 알 수있는 방법이 없습니다 .0 또는 1000이있을 수 있습니다. 그리고 왜?
벤치 마크 없이는 알기가 어렵지만 ArrayList에 많은 항목이 있고 평균 크기가 더 작은 경우 새 ArrayList를 만드는 것이 더 빠를 수 있습니다.
http://www.docjar.com/html/api/java/util/ArrayList.java.html
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
List.clear
목록의 용량을 줄이지 않고 요소를 제거합니다.
groovy:000> mylist = [1,2,3,4,5,6,7,8,9,10,11,12]
===> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
groovy:000> mylist.elementData.length
===> 12
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@19d6af
groovy:000> mylist.clear()
===> null
groovy:000> mylist.elementData.length
===> 12
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@19d6af
groovy:000> mylist = new ArrayList();
===> []
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@2bfdff
groovy:000> mylist.elementData.length
===> 10
여기서 mylist가 지워졌고 보유하고있는 요소에 대한 참조가 무효화되었지만 동일한 배킹 배열을 유지합니다. 그런 다음 mylist는 다시 초기화되어 새로운 백업 배열을 얻었고 이전 배열은 GCed입니다. 따라서 한 방법은 메모리를 잡고 다른 방법은 메모리를 버리고 처음부터 (기본 용량으로) 재 할당합니다. 가비지 수집 변동을 줄이거 나 현재 사용하지 않는 메모리 양을 최소화할지 여부에 따라 더 나은 방법이 있습니다. 목록이 에덴 밖으로 이동할 수있을 정도로 오래 지속되는지 여부는 가비지 수집이 더 비쌀 수 있기 때문에 어느 것이 더 빠른지를 결정하는 요인이 될 수 있습니다.
답은 다음과 같은 다양한 요소에 달려 있다는 것입니다.
- 목록 크기를 미리 예측할 수 있는지 (즉, 용량을 정확하게 설정할 수 있는지)
- 목록 크기가 가변적인지 (즉, 채워질 때마다)
- 두 버전에서 목록의 수명이 얼마나 길고
- 힙 / GC 매개 변수 및 CPU.
이것들은 어느 것이 더 좋을지 예측하기 어렵게 만듭니다. 그러나 나의 직감은 그 차이가 그렇게 크지 않을 것이라는 것입니다.
최적화에 대한 두 가지 조언 :
하지 마십시오 시간을 낭비 응용 프로그램이되지 않는 ...이를 최적화하기 위해 노력하고 객관적으로 너무 느린 및 프로파일 러를 사용하여 측정 알려줍니다 이 성능 핫스팟 있음을. (이 전제 조건 중 하나가 맞지 않을 가능성이 있습니다.)
If you do decide to optimize this, do it scientifically. Try both (all) of the alternatives and decide which is best by measuring the performance in your actual application on a realistic problem / workload / input set. (An artificial benchmark is liable to give you answers that do not predict real-world behavior, because of factors like those I listed previously.)
The first one .clear();
will keep the same list just clear the list.
The second one new ArrayList<Integer>();
creates a new ArrayList
in memory.
Suggestion: First one because that's what is is designed to do.
Tried the below program , With both the approach. 1. With clearing the arraylist obj in for loop 2. creating new New Arraylist in for loop.
List al= new ArrayList();
for(int i=0;i<100;i++)
{
//List al= new ArrayList();
for(int j=0;j<10;j++)
{
al.add(Integer.parseInt("" +j+i));
//System.out.println("Obj val " +al.get(j));
}
//System.out.println("Hashcode : " + al.hashCode());
al.clear();
}
and to my surprise. the memory allocation didnt change much.
With New Arraylist approach.
Before loop total free memory: 64,909 ::
After loop total free memory: 64,775 ::
with Clear approach,
Before loop total free memory: 64,909 :: After loop total free memory: 64,765 ::
So this says there is not much difference in using arraylist.clear from memory utilization perspective.
If there is a good chance that the list will contain as much elements as it contains when clearing it, and if you're not in need for free memory, clearing the list is a better option. But my guess is that it probably doesn't matter. Don't try to optimize until you have detected a performance problem, and identified where it comes from.
list.clear()
is going to keep the same ArrayList but the same memory allocation. list = new ArrayList<int>();
is going to allocate new memory for your ArrayList.
The big difference is that ArrayLists will expand dynamically as you need more space. Therefore, if you call list.clear()
you will still, potentially, have a large amount of memory allocated for an ArrayList that might not be needed.
That said list.clear()
will be faster but if memory maters you might want to allocate a new ArrayList.
I would suggest using list.clear() rather than allocating a new object. When you call the "new" keyword, you are creating more space in memory. In reality, it doesn't matter much. I suppose that if you know how large the list will be, it might be a good idea to create a new space but then specify how large the array will be.
The truth is, it's not going to matter unless you're doing scientific programming. In that case, you need to go learn C++.
참고URL : https://stackoverflow.com/questions/6961356/list-clear-vs-list-new-arraylistinteger
'Programming' 카테고리의 다른 글
렌더링 시간 및 성능 측면에서 패널은 어떤 순서로 가장 효율적입니까? (0) | 2020.07.17 |
---|---|
POST 데이터를 URL 인코딩해야합니까? (0) | 2020.07.17 |
널 포인터에 왜 주소 0이 사용됩니까? (0) | 2020.07.17 |
babel-preset-stage-0, babel-preset-stage-1 등의 차이점은 무엇입니까? (0) | 2020.07.17 |
Java EE 컨테이너의 스폰 스레드가 권장되지 않는 이유는 무엇입니까? (0) | 2020.07.17 |