Lifetime (memory scope) of local variables inside a function

前端 未结 2 668
臣服心动
臣服心动 2020-12-29 04:16
def some_function():
    some_dict = {\'random\': \'values\'}
    a = some_dict[\'random\']
    return a
  1. When is the dictionary some

2条回答
  •  借酒劲吻你
    2020-12-29 04:44

    1. The dictionary some_dict will be created in memory every single time the function is called.
    2. It is deallocated when the function returns.
    3. It is really expensive to recreate the dictionary every single time that the function is called, especially if the dictionary is large. You can instead create the dictionary in the caller function (assuming that the caller itself is only called once) and pass it as a argument to the function some_function().

    For example, consider the function caller() which calls the function callee (some_function() in your question), as in

    def caller():
        callee()
    

    From your usage case, we want to call callee() multiple times, and we need to reuse the same dictionary in callee(). Let's run through the normal usage cases.

    1. Dictionary is generated in callee(). This is the example in your question.

    def caller():
        for loop:    
            callee()
    
    def callee():
        generate dictionary
        do something with dictionary
    

    In this case, every single time callee() is called, you have to generate a new dictionary. This is because as soon as callee() returns, all of its local variables are deallocated. Therefore, you can't "reuse" the same dictionary between different callee()s.

    2. Dictionary is generated in caller() and passed as an argument to callee().

    def caller():
        generate dictionary
        for loop:    
            callee(dictionary)
    
    def callee(dictionary):
        do something with dictionary
    

    In this case, you are generating the dictionary once in caller(), and then passing it to every single callee() function. Therefore, each time that you call callee(), you won't need to regenerate the dictionary.

    The dictionary is passed by reference, so you aren't passing a huge data structure each time you call callee(). I'm not going to go in depth about this (you can find a good explanation here), but in essence, there is negligible cost to pass the dictionary as a parameter to callee().

提交回复
热议问题