Tamaño inesperado de los objetos de Python en la memoria

En este artículo, discutiremos el tamaño inesperado de los objetos de Python en la memoria.

Los objetos de Python incluyen Lista, tupla, Diccionario, etc., tienen diferentes tamaños de memoria y también cada objeto tendrá una dirección de memoria diferente. Tamaño inesperado significa el tamaño de la memoria que no podemos esperar. Pero podemos obtener el tamaño usando la función getsizeof(). Esto devolverá el tamaño de la memoria del objeto python. Esta función está disponible en el módulo sys, por lo que debemos importarla.

Sintaxis :

sys.getsizeof(object)

Ejemplo 1: código de Python para obtener el tamaño inesperado del objeto de string

Una string con un solo carácter consumirá 50 bytes, luego, después de 1 carácter, consumirá n bytes de caracteres.

Ejemplo:

‘e’ consumirá – 50

‘eo’ consumirá – 51

‘eoo’ consumirá – 52

Python3

# import sys module
import sys
  
# get the size of the given string
print(sys.getsizeof('g'))
  
# get the size of the given string
print(sys.getsizeof('ge'))
  
# get the size of the given string
print(sys.getsizeof('gee'))
  
# get the size of the given string
print(sys.getsizeof('geek'))
  
# get the size of the given string
print(sys.getsizeof('geeks'))

Salida :

50
51
52
53
54

Ejemplo 2: programa Python para obtener el tamaño inesperado del objeto entero

El objeto entero tomará 28 bytes

Python3

# import sys module
import sys
  
# get the size of the given integer
print(sys.getsizeof(123))
  
# get the size of the given integer
print(sys.getsizeof(21))

Producción:

28
28

Ejemplo 3: código de Python para obtener un tamaño inesperado del objeto de la lista

Podemos definir la lista como []. Una lista vacía consumirá 72 bytes y consumirá 8 bytes adicionales para cada elemento.

[] – 72

[1] – 72 + 8 = 80

[1,2] – 72 +8 + 8 =88

Python3

# import sys module
import sys
  
# get the size of empty list
print(sys.getsizeof([]))
  
# get the size of list with one element
print(sys.getsizeof([2]))
  
# get the size of list with two elements
print(sys.getsizeof([22, 33]))

Salida :

72
80
88

Ejemplo 4: obtener un tamaño inesperado del objeto del diccionario

Este objeto consumirá 248 bytes independientemente del número de elementos.

Python3

# import sys module
import sys
  
# get the size of empty dictionary
print(sys.getsizeof({}))
  
# get the size of dictionarydictionary with one element
print(sys.getsizeof({'k': 2}))
  
# get the size of list with two elements
print(sys.getsizeof({'k': 2, 'h': 45}))

Salida :

248
248
248

Publicación traducida automáticamente

Artículo escrito por sravankumar8128 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *