Java에서는, 문자열 객체가 생성될 때마다 새로운 주소를 할당하는 방식을 사용합니다. 그러나 Python의 경우 문자열 객체 생성 시 매번 새로운 객체를 만드는 대신 기존에 선언되어 있던 immutable 객체를 사용합니다. 이는 CPython의 최적화 기법인 string interning
에 의한 동작입니다. 따라서 둘 이상의 변수가 메모리의 동일한 문자열 객체를 가리킬 수 있고, 메모리를 절약하게 됩니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = 'PlanB' | |
b = 'PlanB' | |
print(id(a), id(b)) | |
# 4346040648 4346040648 | |
print(id(a) == id(b)) | |
# True | |
print(a is b) | |
# True |
string interning의 규칙
string interning 최적화에는 몇가지 규칙이 있습니다.
- 길이가 0 또는 1인 문자열은 intern
- 컴파일 타임에만 intern : 동적으로 문자열을 만들어내는 경우(포맷팅 등) intern되지 않음
- ASCII 문자, 숫자 또는 언더스코어가 아닌 문자가 속해 있는 경우(!, ? 등) intern되지 않음
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = 'Plan_B' | |
b = 'Plan_B' | |
print(a is b) | |
# True | |
# ASCII 문자, 숫자, 언더스코어로 이루어진 문자열은 intern | |
a = 'PlanB!' | |
b = 'PlanB!' | |
print(a is b) | |
# False | |
# ASCII 문자, 숫자, 언더스코어 외의 문자가 들어가면 intern되지 않음 | |
a = '!' | |
b = '!' | |
print(a is b) | |
# True | |
# 길이가 0 또는 1이면 intern |
'Python 계열 > Python 레거시 글' 카테고리의 다른 글
[Python] Decorator (0) | 2018.07.21 |
---|---|
[Python] Closure (0) | 2018.07.20 |
[Python] 함수 인자의 기본값 평가 (0) | 2018.07.14 |
[Python] @property와 setter (0) | 2018.07.13 |
[Python] Keyword exclusive argument (0) | 2018.07.11 |