65 lines
1.9 KiB
Org Mode
65 lines
1.9 KiB
Org Mode
:PROPERTIES:
|
|
:ID: c0d562c7-9d2f-4f35-b7b1-f6b6ca5273f9
|
|
:mtime: 20220501162112
|
|
:ctime: 20220501153651
|
|
:END:
|
|
#+title: 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é.
|
|
#+BEGIN_SRC python :results output
|
|
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}')
|
|
#+END_SRC
|
|
|
|
#+RESULTS:
|
|
: 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~
|
|
|
|
#+BEGIN_SRC python :results output
|
|
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}')
|
|
#+END_SRC
|
|
|
|
#+RESULTS:
|
|
: 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
|
|
|
|
* Références
|
|
* [[https://pythonsimplified.com/optimization-in-python-interning/][Optimization in Python — Interning - pythonsimplified]]
|
|
* [[https://stackoverflow.com/questions/55347581/why-does-the-is-operator-behave-differently-in-a-script-vs-the-repl][Why does the `is` operator behave differently in a script vs the REPL? - Stack-Overflow]]
|