python 객체 생성과 interning

LULLU·2022년 8월 24일

python

목록 보기
1/1
post-thumbnail

python 객체 생성 방식

  • 모든 데이터 타입은 <class 'object'>의 subclass
    • tip: bool은 int의 subclass이다!
    • 변수는 객체를 참조함
      • C에서의 포인터와 유사
      • 객체를 참조만 하기에 변수에는 타입이 없음 → dynamic typing
      • 객체를 참조하는 변수가 없어지면 객체의 메모리 할당이 해제된다. (refcount가 0이 될때)

int, str type의 특징

  • built-in type
  • immutable type : 객체 내부 값을 수정할 수 없다.
    : string의 slicing, concatenation → 새로운 string 객체 생성
  • python 실행 과정에서 생성되는 int, str 객체들
    → user code 실행 전에 이미 memory에 위치하게됨
    interning :

    storing only one copy of each distinct string value in memory

integer interning

  • -5~256의 값은 각각의 객체가 1개
    https://docs.python.org/3.8/c-api/long.html?highlight=fromlong#c.PyLong_FromLong

    The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. `

    • 해당 범위의 integer 값들은 python 실행 시 메모리에 위치해, 계속 재사용됨.
      → 새로운 변수를 만들면, 새로운 int 객체가 만들어지지 않고 항상 intern된 int 객체를 참조함.
      • 예시 코드
        • 256을 참조하는 변수 → 같은 객체를 참조함.
        • 65537를 참조하는 변수 → 다른 객체를 참조함.
  • optimizer의 precalculation

    • compile time에 가능한 계산을 미리 수행하여 코드 최적화
      → 256보다 큰 int도 interning이 된다.
      1. (왼쪽) code 두줄이 동시에 입력되어 compile time 최적화가 적용됨. 따라서 큰 값의 integer도 interning이 됨.
      2. (오른쪽) code 두줄이 따로 입력되는 경우에는 큰 값의 integer는 interning되지 않음.

    • -5~256 범위의 int는 run-time 할당에도 intern된 값을 참조
      1. code 두줄이 따로 입력되어도, -5~256의 integer를 가리키는 변수는 항상 기존에 interning된 값을 참조한다.

string interning

  • optimizer의 precalculation 과정에서 string interning이 적용된다.
  • string interning 기준
    1. a-z, A-Z, 0-9, _로만 이루어진 string
      underscore가 아닌 space, hyphen이 들어간 string은 interning이 되지 않는다.
    2. 기준 길이 이하의 string


      20자리를 넘는 string은 interning이 되지 않는다. (python 3.6)
  • manual interning
    • run-time concatenation은 기본적으로 interning을 하지 않음
    • sys.intern() 으로 manually interning이 가능하다.
      >>> import sys
      >>> s1 = "strin"
      >>> s2 = s1 + "g"
      >>> s2 is "string"
      False
      >>> sys.intern(s3) is "string"
      True

interning의 의의

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

  • Advantages
    1. Saving Memory
    2. Fast Comparisons 
      • =가 아닌 is로 비교
    3. Fast Dictionary Lookups
        1. 와 동일한 이유
  • Disadvantages
    1. Memory Cost
      • string이 많고, 비교는 적을 때는 유용하지 않다.
    2. Time Cost
      • intern() 함수의 호출 비용이 높음 (interned table을 계속 관리해야하는 소요)
    3. Multi-threaded Environments
      • interned memory는 global resource → synchronization 과정의 cost를 고려해야함.

0개의 댓글