Map의 효율적인 스트리밍
3039 단어 J2EE
코드에서 다음과 같은 역행을 채택하였다
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]
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
layui- 동적 렌더링 드롭다운 상자 (백그라운드에서 드롭다운 상자 값 가져오기) & 드롭다운 상자 기본 선택 설정동적 렌더 드롭다운 상자 드롭다운 상자 기본 선택 설정...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.