简体   繁体   中英

When should I store the result of a function as a variable in python?

Suppose a function my_list(obj) returns a list. I want to write a function that returns the single element of my_list(obj) if this list has length one and False otherwise. My code is

def my_test(obj):
    if len(my_list(obj)) == 1:
        return my_list(obj)[0]
    return False

It just dawned on me that the code

def my_test(obj):
    L = my_list(obj)
    if len(L) == 1:
        return L[0]
    return False

might be more efficient since it only calls my_list() once. Is this true?

The function my_list() could possibly be computationally intensive so I'm curious if there is a difference between these two blocks of code. I'd happily run a test myself but I'm not quite sure how to do so. I'm also curious if it is better practice in general to store the result of a function as a variable if the function is going to be called more than once.

You are correct. The second block would be more efficient since it only calls my_list() once. If my_list() isn't particularly computationally expensive, it's unlikely you will notice a difference at all. If you know it will be expensive, on the other hand, it is a good idea to save the result where you can if it does not hamper readability (however, note the caveat in @Checkmate's answer about memory for a possible exception).

However, if my_list() has side effects , or if it's return value may change between those two invocations, you may not want to save it (depends on if you want to trigger the side effects twice or need to receive the changed return value).

If you wanted to test this yourself, you could use time.time like this :

import time

t0 = time.time()
my_test()
t1 = time.time()

total = t1-t0

to get the time for my_test() . Just run both functions and compare their time.

To answer your question on whether it is generally better to store the result of a function as a variable if it is going to be called more than once: it depends. In terms of readability, it's really up to you as a programmer. In terms of speed, storing the result in a variable is generally faster than running the function twice.

Storing the result can, however, uses memory, and if you're storing an unusually large variable, the memory usage can actually lead to longer running time than simply calling the function. Further, as noted above, running a function can do more than just storing the result in a variable, so running a function a different number of times can give a different result.

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