ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스트링을 new 로 생성하는 것과 " " 로 생성하는 것의 차이
    개발/Java 2021. 7. 13. 01:06

     

    " "로 생성한 스트링의 경우 문자열이 힙 영역에 존재하는 String Pool에 상수로서 저장되고 그 값을 꺼내씁니다.

    동일한 문자열이 반복적으로 사용될 때, 문자열을 새로 생성하지 않고 String Pool에서 기존에 존재하는 상수를 꺼내옴으로써 메모리를 절약합니다.

     

    💡
    String Pool은 java6 까지는 Non-heap Area에 속한 PermGen에 위치했는데, Java7 부터 heap 으로 이동하였습니다.

     

    반면 new로 생성한 스트링은 다른 객체들처럼 heap 영역에 객체로서 생성됩니다.

    https://stackoverflow.com/questions/41908321/difference-between-heap-memory-and-string-pool/41908347

     

    • 아래 테스트를 통과합니다.
        @Test
        void StringPool에서_동일한_문자열을_가져온다() {
            String hello1 = "hello"; // string pool 
            String hello2 = "hello"; // string pool에서 hello1 과 같은 상수를 가져온다.
            assertThat(hello1 == hello2).isTrue();
        }
    
        @Test
        void 같은_문자열이지만_동일하지_않다() {
            String hello = "hello"; // string pool (in heap)
            String newHello1 = new String("hello"); // heap에 생성
    				assertThat( hello == newHello1).isFalse();
    
            String newHello2 = new String("hello"); // heap에 또 생성   
            assertThat(newHello1 == newHello2).isFalse();
    
            // 둘은 '동일'하진 않지만 '동등'하다.
            assertThat( newHello1.equals(newHello2) ).isTrue();
        }

     

    추가로

    String 클래스의 메소드중 intern() 이라는 네이티브 메소드가 있는데, String Pool에 있는 상수를 가져옵니다.

        @Test
        void intern_메소드는_StrigPool에_문자열을_추가한다() {
            String hello = "hello";
            String newHello = new String("hello");
            assertThat( hello == newHello).isFalse(); // hello와 newHello는 동일하지 않다.
    
    				
            newHello = newHello.intern(); // newHello와 동일한 상수를 String Pool에서 꺼낸다. 
            assertThat(hello == newHello).isTrue(); // hello와 newHello가 동일해졌다.
        }

     

    https://stackoverflow.com/questions/41908321/difference-between-heap-memory-and-string-pool/41908347

     

    댓글

Designed by Tistory.