본문 바로가기
목차
Python

[Py] String Interning

by ds31x 2025. 7. 7.
728x90
반응형

https://stackabuse.com/guide-to-string-interning-in-python/

Intern(인터닝)은 Python에서 문자열 최적화 기법의 하나로서,
동일한 문자열을 메모리에 한 번만 저장하고 여러 변수가 같은 객체를 참조하도록 하는 기법을 가리킴.

# Normal case (not interned)
a = "hello world"
b = "hello world"
print(a is b)  # False (different objects)
print(id(a), id(b))  # Different memory addresses

# Interned case
a = "hello"  # Automatically interned
b = "hello"
print(a is b)  # True (same object)
print(id(a), id(b))  # Same memory address

 

더보기

Intern은 명사로 사용될 때, 수습 이나, 동사에서는 억류하다, 수용하다, 감금하다 의 뜻을 가짐.

string interning은 이 동사의 뜻에서 유래하여 PVM에서 시스템의 내부 문자열 풀에 수용시키는 것을 의미함.

여기 한 번 들어가면 PVM이 종료될 때까지 못 나옴. ^^;;


Automatic Interning

다음의 경우 자동으로 interning 이 수행됨

  • 식별자처럼 생긴 문자열 (변수명, 함수명 등에 사용 가능한 형태)
    • 변수명의 규칙을 따르는 경우를 가리킴: 변수명이 될 수 있는 문자열은 interning!
    • 공백없이 영어 대소문자_ (under score), 숫자 로 구성된 경우
    • 숫자로 시작하면 변수명은 안되지만, interning은 됨.
  • 컴파일 시점에 생성되는 문자열 리터럴
  • 길이가 0 또는 1인 문자열
# 자동 인터닝되는 경우
a = "hello"      # 식별자 형태
b = "hello"
print(a is b)    # True

a = "hello123"   # 알파벳 + 숫자
b = "hello123"
print(a is b)    # True

a = ""           # 빈 문자열
b = ""
print(a is b)    # True

a = "a"          # 단일 문자
b = "a"
print(a is b)    # True

# 자동 인터닝되지 않는 경우
a = "hello world"  # 공백 포함
b = "hello world"
print(a is b)      # False (CPython 구현에 따라 다를 수 있음)

a = "hello-world"  # 하이픈 포함
b = "hello-world"
print(a is b)      # False

Explicit Interning

sys.intern()을 통해 명시적으로 처리도 가능.

자주 사용되는 고정 문자열, 설정 키 (dict에서 사용되는), 자주 사용되는 상수값 등은 미리 해두면 성능이 향상됨.

사용자 입력으로 얻어지는 동적인 문자열은
인터닝하면 메모리 누수 발생함.

import sys

# 강제 인터닝
a = sys.intern("hello world with spaces")
b = sys.intern("hello world with spaces")
print(a is b)  # True

# 일반적인 경우와 비교
c = "hello world with spaces"
d = "hello world with spaces"
print(c is d)  # False

print(a is c)  # False (인터닝된 것과 안된 것은 다름)

장단점

  • 장점
    • 메모리 절약: 동일한 문자열을 한 번만 저장
    • 비교 속도 향상: is 연산자로 빠른 비교 가능
    • 해시 계산 최적화: 한 번 계산된 해시값 재사용
  • 단점
    • 메모리 해제 불가: 인터닝된 문자열은 프로그램 종료까지 메모리에 남음
    • 초기 오버헤드: 인터닝 과정에서 약간의 시간 소요
    • 메모리 누수 위험: 너무 많은 문자열을 인터닝하면 메모리 사용량 증가

같이 보면 좋은 자료들

다음 URL에서 "literal의 경우" 절을 읽어볼 것: https://dsaint31.tistory.com/499

 

[Python] Assignment와 Shallow Copy, Deep Copy

시작하기 전https://ds31x.tistory.com/404 [Py] 객체(object)에 대한 정보 확인하기Python에서 object(객체)란?type, id, refcount, value 를 속성으로 가지고 있는 a chunk of data.https://dsaint31.tistory.com/517 [Python] Variable (an

dsaint31.tistory.com

https://gist.github.com/dsaint31x/add62bd29600918890c4bd8c433f0665

 

string_interning.ipynb

string_interning.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

728x90