简体   繁体   中英

Python import statement inside and outside a function. What is better for the memory?

When memory issues are critical, do I save some memory when I do my python imports inside a function, so as to when the call finishes everything will be discarder from memory? Or this cumbers more my memory and CPU especially when I do a lot of calls of the specific function? (The user does the calls and I do not know in advance how many she will do). What are the memory implications of this difference?

When you import a module, any/all module objects/functions/etc are cached so that importing the same module again is a no-op. Subsequently these objects/functions/etc will not be freed when the local names referring to them go out of scope. This only affects functions and objects defined globally within the module and it's very likely that there won't be a lot of those, so it's probably not something to worry about.

To specifically answer your question, there is effectively no difference in terms of performance unless the import is inside a function or branch which is never executed. In that rare case, having it inside the branch or function is slightly faster/less resource intensive, but it won't gain you much.

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