Python Memory Model

前端 未结 4 1763
半阙折子戏
半阙折子戏 2020-12-24 09:00

I have a very large list Suppose I do that (yeah, I know the code is very unpythonic, but for the example\'s sake..):

n = (2**32)**2
for i in xrange(10**7)
          


        
4条回答
  •  长情又很酷
    2020-12-24 10:07

    You have only one variable n, but you create many i**2.

    What happens is that Python works with references. Each time you do array[i] = n you create a new reference to the value of n. Not to the variable, mind you, to the value. However, in the second case, when you do array[i] = i**2 you create a new value, and reference this new value. This will of course use up much more memory.

    In fact, Python will keep reusing the same value and just use references to it even if it's recalculated. So for example:

    l = []
    x = 2
    for i in xrange(1000000):
        l.append(x*2)
    

    Will generally not use more memory than

    l = []
    x = 2
    for i in xrange(1000000):
        l.append(x)
    

    However, in the case of

    l = []
    x = 2
    for i in xrange(1000000):
        l.append(i)
    

    each value of i will get a reference and therefore be kept in memory, using up a lot of memory compared to the other examples.

    (Alex pointed out some confusion in terminology. In python there is a module called array. These types of arrays store integer values, instead of references to objects like Pythons normal list objects, but otherwise behave the same. But since the first example uses a value that can't be stored in such an array, this is unlikely to be the case here.

    Instead the question is most likely using the word array as it's used in many other languages, which is the same as Pythons list type.)

提交回复
热议问题