0

I am confused :

(1) when int convert to bytearray (or str convert to bytearray) ,why its memory space increase ?

a=1  # int 
print 'space of int ',sys.getsizeof(a)
b=bytearray(a) # convert
print 'space of b ',sys.getsizeof(b)

s='h' # str 
print 'space of s',sys.getsizeof(s)
b2=bytearray(s)
print 'space of b2',sys.getsizeof(b2)

output:

space of a  12
space of b  26
space of s 22
space of b2 26

(2) I have read this , In-memory size of a Python structure and I have known different types of a python object has different memory size.But I can't figure out its principle.

Community
  • 1
  • 1
RY_ Zheng
  • 3,041
  • 29
  • 36
  • 2
    Presumably it is due to different amounts of overhead for the two types. However, note that `bytearray(1)` does not create a bytearray containing the bytes of the integer 1; it creates a bytearray containing a single zero byte. Be sure to read [the documentation](https://docs.python.org/2/library/functions.html#bytearray). – BrenBarn Mar 23 '15 at 16:32
  • "If it is an integer, the array will have that size and will be initialized with null bytes." thank you ~ – RY_ Zheng Mar 29 '15 at 05:08

1 Answers1

1

Every Python type has a minimal amount of space it will use, even if empty. This is commonly called the overhead.

Container datatypes (dict, list, tuple, bytearray, set, etc.) will typically have more overhead than simple types (str, int, etc.) because there is more to keep track of (size, pointers to elements, etc.).

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237