简体   繁体   中英

Why is an int in a list and in an compact array the same size? (24bytes)

I was just reading that a compactArray defined as "i" should yield an array that hold integers with 2 or 4 bytes, but executing this snippet i am still getting 24bytes, which is the same as i would use integer lists.

import array
import sys
lowLevelArray = array.array("i", [1,2,3])
print sys.getsizeof(lowLevelArray[0])
pythonList = [1,2,3]
print sys.getsizeof(pythonList[0])

Output:

24

24

Because once you retrieve the integer it has to be wrapped in a python object so you can work with it. Everything in python is an object, it has no concept of primitives (even though the underlying implementation uses them).

The array object is more space efficient; it's 4 bytes per int it holds, plus 56 bytes overhead:

>>> sys.getsizeof(array.array("i", [1,2,3])
68L
>>> sys.getsizeof(array.array("i", range(1000))
4056L

However, when you do

>>> sys.getsizeof(lowLevelArray[0])

it first evaluates lowLevelArray[0] , which of course returns a normal integer, and then shows the size used by that . Which is completely unrelated to the fact that you also have an array that happens to hold the same value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM