TIL- String Pool

kyoungyeon·2022년 10월 13일
0

TIL

목록 보기
53/110
post-thumbnail

status

메모리 존나어렵다
string이 heap string pool에 올라가는데,
근데 string 연산은 또 왜 다른곳에 올라가는데!
그래서 공부해봄

try:

// Program 1: Comparing two references to objects 
// created using literals. 
import java.util.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        String s1 = "abc"; 
        String s2 = "abc"; 
  
        // Note that this == compares whether 
        // s1 and s2 refer to same object or not 
        if (s1 == s2) 
           System.out.println("Yes"); 
        else
           System.out.println("No"); 
    } 
} 
Output:
Yes

// Program 2: Comparing two references to objects 
// created using new operator. 
import java.util.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        String s1 = new String("abc"); 
        String s2 = new String("abc"); 
  
        // Note that this == compares whether 
        // s1 and s2 refer to same object or not 
        if (s1 == s2) 
           System.out.println("Yes"); 
        else
           System.out.println("No"); 
    } 
} 
Output:
No

  • detail :
    • literal 상수 ("")만 풀에 올라갈것
    • 연산되는 변수는 heap -string Pool 에 올라가는게 아니라 stack 에 쌓임
    • new 연산자는 메모리 효율이 좋지 않다. 위와 같이 각각의 heap 메모리 공간을 차지하기 때문.
    • String 리터럴로 하면 계속해서 참조 할수 있음 (그림참조)
    • string pool 에 올라간 문자는 편집을 못함
    • string Buffer가 나옴 => 여기선 메모리 일부공간에 할당을 해놓고 string이 수정, 변경 가능함.
    • String 자체는 메모리 주소값이 변경되기때문에 연산마다 아예 값이 바뀌어버림.

Goals

- 좀 더 heap 에 대해서 정리해보자
- stack, queue,heap 개념에 대한 혼동이 있음.
- 질문한 내용 정리해서 공부하기
 

Reference

JV StringPool
string-pool

profile
🏠TECH & GOSSIP

0개의 댓글