Files
org-roamings/20220501153651-interning_optimization.org
2022-06-04 12:57:39 +02:00

1.9 KiB

Interning optimization

Introduction

  • Concerne CPython,
  • Consiste en la réutilisation d'objet plutôt que d'en recrééer.

Integer interning

  • Au démarrage, CPython pré-charge en mémoire les entiers de -5 à 256,
  • A chaque fois qu'un entier compris dans cet intervalle est utilisé, celui-ci fait référence à un entier pré-chargé.
a = 100
b = 100

print(f'Memory address of a: {id(a)}')
print(f'Memory address of b: {id(b)}')
print(f'a is b: {a is b}')
Memory address of a: 9792128
Memory address of b: 9792128
a is b: True

String interning

  • Au démarrage, CPython pré-charge en mémoire les chaines de caractères présentes dans le code et de longueur <= 4096,
  • Il est possible de forcer le pré-chargement en mémoire d'une chaine à l'aide de sys.intern
from random import choice
from string import printable
from sys import intern

a = "Data"
b = "Data"

print(f'Memory address of a: {id(a)}')
print(f'Memory address of b: {id(b)}')
print(f'a is b: {a is b}')

c = intern(''.join(choice(printable) for _ in range(4097)))
d = c

print(f'Memory address of c: {id(c)}')
print(f'Memory address of d: {id(d)}')
print(f'c is d: {c is d}')
Memory address of a: 139629084500336
Memory address of b: 139629084500336
a is b: True
Memory address of c: 28459264
Memory address of d: 28459264
c is d: True