Map의 효율적인 스트리밍

3039 단어 J2EE
[quote][b] 장면: [/b] 간혹 생산 환경의 어떤 기계의 CPU 사용률이 매우 높은데 포지셔닝을 통해 큰 HashMap(HashMap에 대량의 데이터가 저장되어 있는데 예를 들어 1W개)이 순환해서 일어난 것이다.[/quote]
코드에서 다음과 같은 역행을 채택하였다

for(Iterator ite = map.keySet().iterator(); ite.hasNext();){
Object key = ite.next();
Object value = map.get(key);
}

맵 클래스의 get(key) 방법으로value를 가져올 때hashCode를 두 번 계산하여 CPU 자원을 소모합니다.entrySet의 방식을 사용하면 맵 대상은 키-value를 저장한 원시 데이터 구조 대상을 직접 되돌려주고 반복 과정은 오류 코드에 시간이 걸리는hashCode 계산을 하지 않아도 된다.이는 빅데이터 양에서 특히 뚜렷하게 나타난다.
다음은 HashMap.get () 방법의 원본 코드:

public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}

올바른 용도는 다음과 같습니다.

for(Iterator ite = map.entrySet().iterator(); ite.hasNext();){
Map.Entry entry = (Map.Entry) ite.next();
entry.getKey();
entry.getValue();
}

비교 테스트
  
public class HashMapTest {
public static void getFromMap(Map map){
for(Iterator ite = map.keySet().iterator(); ite.hasNext();){
Object key = ite.next();
Object value = map.get(key);
}
}
public static void getFromMapByEntrySet(Map map){
for(Iterator ite = map.entrySet().iterator(); ite.hasNext();){
Map.Entry entry = (Map.Entry) ite.next();
entry.getKey();
entry.getValue();
}
}

public static void main(String[] args) {
Map map = new HashMap();
for(int i=0;i<200000;i++){
map.put("key"+i, "value"+i);
}
long currentTime = System.currentTimeMillis();
getFromMap(map);
long currentTime2 = System.currentTimeMillis();
getFromMapByEntrySet(map);
long currentTime3 = System.currentTimeMillis();
System.out.println(currentTime2-currentTime);
System.out.println(currentTime3-currentTime2);
}

}

실행 결과:
 
16
0

비교를 통해 뚜렷한 차이를 볼 수 있다.
가장 자주 사용하는 스트리밍 방법도 있는데, 그 효과도 그다지 좋지 않아, 사용을 권장하지 않는다.
  
for(Iterator i = map.values().iterator(); i.hasNext();) {
Object temp = i.next();
}

[url=http://item.taobao.com/item.htm?id=23063096911][img]http://img02.taobaocdn.com/bao/uploaded/i2/10118022169782183/T1nSCnXpNaXXXXXXXX_!!0-item_pic.jpg_310x310.jpg[/img][/url]

좋은 웹페이지 즐겨찾기