첫째, 난 당신이 ArrayList
이 Vector
보다 더 나은 선택을하는 것과 같은 이유로, 대신 Hashtable
의 HashMap
를 사용하는 것이 좋습니다.
제 추측은 ArrayList
를 반복하는 단계 Hashtable
년대 (또는 HashMap
년대) entrySet()
메소드에 의해 리턴 된 Set
통해 반복보다 빠를 것입니다. 그러나 알 수있는 유일한 방법은 프로파일 링하는 것입니다.
분명히 디스플레이 목록을 변경하면 (마지막 요소를 추가하거나 잘라내는 것 외에) HashMap
은 ArrayList
보다 빠릅니다.
편집 그래서 난 내 자신의 조언을 따라 벤치 마크.
import java.util.*;
public class IterTest {
static class Thing {
Thing(String name) { this.name = name; }
String name;
}
static class ArrayIterTest implements Runnable {
private final ArrayList<Thing> list;
ArrayIterTest(ArrayList<Thing> list) {
this.list = list;
}
public void run() {
int i = 0;
for (Thing thing : list) {
++i;
}
}
}
static class ArraySubscriptTest implements Runnable {
private final ArrayList<Thing> list;
ArraySubscriptTest(ArrayList<Thing> list) {
this.list = list;
}
public void run() {
int i = 0;
int n = list.size();
for (int j = 0; j < n; ++j) {
Thing thing = list.get(j);
++i;
}
}
}
static class MapIterTest implements Runnable {
private final Map<String, Thing> map;
MapIterTest(Map<String, Thing> map) {
this.map = map;
}
public void run() {
int i = 0;
Set<Map.Entry<String, Thing>> set = map.entrySet();
for (Map.Entry<String, Thing> entry : set) {
++i;
}
}
}
public static void main(String[] args) {
final int ITERS = 10000;
final Thing[] things = new Thing[1000];
for (int i = 0; i < things.length; ++i) {
things[i] = new Thing("thing " + i);
}
final ArrayList<Thing> arrayList = new ArrayList<Thing>();
Collections.addAll(arrayList, things);
final HashMap<String, Thing> hashMap = new HashMap<String, Thing>();
for (Thing thing : things) {
hashMap.put(thing.name, thing);
}
final ArrayIterTest t1 = new ArrayIterTest(arrayList);
final ArraySubscriptTest t2 = new ArraySubscriptTest(arrayList);
final MapIterTest t3 = new MapIterTest(hashMap);
System.out.println("t1 time: " + time(t1, ITERS));
System.out.println("t2 time: " + time(t2, ITERS));
System.out.println("t3 time: " + time(t3, ITERS));
}
private static long time(Runnable runnable, int iters) {
System.gc();
long start = System.nanoTime();
while (iters-- > 0) {
runnable.run();
}
return System.nanoTime() - start;
}
}
그리고 여기에 일반적인 실행에 대한 결과 있습니다 : 분명히 ArrayList에를 사용하여
t1 time: 41412897
t2 time: 30580187
t3 time: 146536728
가 (3 ~ 4 배 정도) 큰 승리는 HashMap 이상 여기 내가 사용하는 코드는 적어도 HashMap을 통해 반복하는 스타일을 위해서. 배열 반복자가 배열 첨자보다 느린 이유는 생성되고 가비지 수집되어야하는 모든 반복자 개체 때문입니다.
메모리 크기가 많은 Intel 1.6GHz 쿼드 코어 Windows 컴퓨터에서 Java 1.6.0_26 (64 비트 JVM)을 사용하여이 작업을 수행했습니다.
Absolutelyly answer, 큰 시간에 고마워. –