Java에서 IdentityHashMap과 HashMap의 차이점 + 성능 비교
게시 됨: 2021-10-19
언젠가는 equality operator (==)
를 기반으로 Map의 Key를 비교해야 하는 특별한 경우가 있습니다. 등호 연산자(==)는 두 키의 참조(메모리 주소)를 두 개의 다른 숫자로 비교합니다.
반면에 HashMap은 equals()
메소드의 도움으로 Key의 고유성을 비교하는 Java Collection Framework 컴포넌트로 가장 많이 사용된다.
또한 IdentityHashMap
은 object.hashCode()
의 해시를 사용하지 않고 System.identityHashCode(object)
를 사용합니다. 런타임 중에 해시 코드가 변경되는 변경 가능한 개체에 대해 IdentityHashMap을 사용할 수 있습니다.
on String Object
적용되는 equals()
및 ==
에 대해 자세히 알아보려면 https://crunchify.com/how-to-override-equals-and-hashcode-method-in-java/ 자습서를 따르세요.
위의 equals() 및 == 동작을 보여주는 기본 테스트:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package crunchify . com . tutorials ; import java . util . HashMap ; import java . util . IdentityHashMap ; import java . util . Map ; /** * @author Crunchify.com * */ public class CrunchifyIdenityHashMapVsHashMapSample { public static void main ( String [ ] args ) { Map < String , String > crunchifyIdentityHashMap = new IdentityHashMap < String , String > ( ) ; Map < String , String > crunchifyHashMap = new HashMap < String , String > ( ) ; // Let's checkout what happens when we put Unique Key to IdentityHashMap crunchifyIdentityHashMap . put ( "Company" , "Crunchify" ) ; // this considered different object for == operator crunchifyIdentityHashMap . put ( new String ( "Company" ) , "Google" ) ; crunchifyIdentityHashMap . put ( "Company" , "Facebook" ) ; System . out . println ( "crunchifyIdentityHashMap KeySet Size: " + crunchifyIdentityHashMap . keySet ( ) . size ( ) ) ; // Let's checkout what happens when we put Unique Key to HashMap crunchifyHashMap . put ( "Company" , "Crunchify" ) ; // key1.equals(key2) returns true hence it removes the old value crunchifyHashMap . put ( new String ( "Company" ) , "Google" ) ; crunchifyHashMap . put ( "Company" , "Facebook" ) ; System . out . println ( "crunchifyHashMap KeySet Size: " + crunchifyHashMap . keySet ( ) . size ( ) ) ; } } |
결과:
1 2 |
crunchifyIdentityHashMap KeySet Size : 2 crunchifyHashMap KeySet Size : 1 |
두 맵에서 성능 테스트를 수행해 보겠습니다.
- 자바 클래스 생성:
CrunchifyIdentityHashMapVsHashMapPerformance
.java
-
startCrunchifyTest()
- 수백만 단위의 랜덤 맵 크기 생성
-
crunchifyString[]
문자열 배열 객체를 위에서 생성된 텍스트와 함께 생성 및 초기화:This is Crunchify's Test # number
-
crunchifyCompareIdentityHashMapVsHashMap(String[] crunchifyString , Map<String, Integer> crunchifyMap , String name )
- 모든 필수 매개변수를 이 메소드에 전달하십시오.
-
crunchifyMap
은 IdentityHashMap / HashMap 값을 갖습니다. - crunchifyString[]을 반복하고 Map에 값을 넣습니다. 이 작업에는 시간이 걸립니다.
- crunchifyString[]을 반복하고 Map에서 값을 가져옵니다. 이 작업은 시간이 걸립니다.
- 위의 두 작업에 대한 실행 시간을 알아내서 위의 작업 중 어느 것이 더 나은지 비교할 수 있습니다. IdentityHashMap 또는 HashMap
- 위 결과 인쇄
- 위의 작업 2와 3을 총 8회 수행합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
package crunchify . com . tutorials ; import java . util . HashMap ; import java . util . IdentityHashMap ; import java . util . Map ; import java . util . Random ; /** * @author Crunchify.com * */ public class CrunchifyIdentityHashMapVsHashMapPerformance { static Random rand = new Random ( ) ; private static void startCrunchifyTest ( ) { // Let's run test for 5 times for ( int i = 0 ; i < 15 ; ++ i ) { // Let's create random Map size which we will use in IdentityHashMap and HashMap int randomMapSize = 1000000 + rand . nextInt ( 9000000 ) ; String [ ] crunchifyString = new String [ randomMapSize ] ; for ( int j = 0 ; j < randomMapSize ; ++ j ) // Assign below string to crunchifyString Object crunchifyString [ j ] = "This is Crunchify's Test #" + j ; System . out . println ( "\nIteration # " + i + " - Creating String with size: " + randomMapSize ) ; crunchifyCompareIdentityHashMapVsHashMap ( crunchifyString , new HashMap < String , Integer > ( randomMapSize ) , "HashMap" ) ; // Runs the garbage collector System . gc ( ) ; crunchifyCompareIdentityHashMapVsHashMap ( crunchifyString , new IdentityHashMap < String , Integer > ( randomMapSize ) , "IdentityHashMap" ) ; // Runs the garbage collector System . gc ( ) ; } } /** * @param crunchifyString * @param crunchifyMap * : IdentityHashMap / HashMap * @param name */ private static void crunchifyCompareIdentityHashMapVsHashMap ( String [ ] crunchifyString , Map < String , Integer > crunchifyMap , String name ) { long start = System . currentTimeMillis ( ) ; // put crunchifyString String[] to map for ( int put = 0 ; put < crunchifyString . length ; ++ put ) crunchifyMap . put ( crunchifyString [ put ] , put ) ; boolean result = false ; for ( int get = 0 ; get < crunchifyString . length ; ++ get ) { if ( crunchifyMap . get ( crunchifyString [ get ] ) ! = get ) result = true ; } System . out . println ( name + " time taken : \t" + ( System . currentTimeMillis ( ) - start ) / 1000. + " sec" ) ; // Check for result discrepancy if ( crunchifyMap . size ( ) ! = crunchifyString . length ) System . out . println ( "Please check size. Test failed" ) ; if ( result ) System . out . println ( "Result failed.." ) ; } public static void main ( String [ ] args ) { System . out . println ( "IdentityHashMap Vs. HashMap comparison Test started..." ) ; // method to compare IdentityHashMap and HashMap startCrunchifyTest ( ) ; } } |
결과:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
IdentityHashMap Vs . HashMap comparison Test started . . . Iteration # 0 - Creating String with size: 6964175 HashMap time taken : 3.155 sec IdentityHashMap time taken : 1.517 sec Iteration # 1 - Creating String with size: 6556459 HashMap time taken : 3.415 sec IdentityHashMap time taken : 1.466 sec < == IdentityHashMap gives better result for large object Iteration # 2 - Creating String with size: 9567664 HashMap time taken : 4.173 sec IdentityHashMap time taken : 2.339 sec < == better Iteration # 3 - Creating String with size: 4230755 HashMap time taken : 0.372 sec IdentityHashMap time taken : 0.911 sec Iteration # 4 - Creating String with size: 7821718 HashMap time taken : 1.096 sec IdentityHashMap time taken : 0.812 sec Iteration # 5 - Creating String with size: 8125421 HashMap time taken : 4.883 sec IdentityHashMap time taken : 1.876 sec < == better Iteration # 6 - Creating String with size: 3166432 HashMap time taken : 0.537 sec IdentityHashMap time taken : 0.708 sec Iteration # 7 - Creating String with size: 2821415 HashMap time taken : 0.227 sec IdentityHashMap time taken : 0.621 sec |
관찰:
결과에서 볼 수 있듯이 큰 맵의 경우 IdentityHashMap이 훨씬 더 잘 수행됩니다. 왜요? IdentityHashMap doesn't use equals() and hashcode() methods
.

참고로:
Map에서 값을 넣고 가져오기 위해 수행하는 위의 작업은 CPU를 매우 많이 사용합니다.
