简体   繁体   中英

Python mutable vs immutable dictionary memory usage

I'm having trouble figuring this out as Python's getsizeof() doesn't return the memory consumption of objects the dictionary refers to.

If I had a few functions that could be called depending on a given input:

def foo(x):
    mapping = {'a':func1,
               'b':func1,
               'c':func2,
               'd':func2,
               'e':func2,
               'f':func3,
               ...etc.}

    return mapping[x]()

and some of the inputs resulted in the same function being called, is storing multiple copies (or is it references?) of the function going to result in a larger memory footprint?

I'm trying to determine if it would be more memory efficient to create an intermediary dictionary that stores only one copy of the function:

functions = {0:func1,
             1:func2,
             2:func3,
             ...etc.}

and replace all the function values in "mapping" with the corresponding integer to save space. I am somewhat aware of how mutable and immutable objects work in Python and my initial conclusion is that all values that refer to the same function do not result in more copies of the function taking up memory. Is this correct?

In a somewhat related question, if I were to print out an objects id, using id(), do all objects that have the same id refer to the same location in memory (and therefore not take up more memory in a dictionary)?

The values in Python dicts are always references. There's no need for the intermediate dict. id (in CPython) gets a number based on the memory address of an object. If the object gets garbage collected then a different object may aquire that id, but at any given time an id is unique to one object.

It is possible to generate multiple function objects from the same source code but with different lexical closure data. Closure cells do have to take memory.


Early optimization is the root of evil. Don't worry about details like this until it actually becomes important for your program, usually if running on limited hardware or when using enormous numbers of objects. (See also, __slots__ .)

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