I am often tempted to import modules in narrow contexts where they are needed. For example in the body of a function that utilises the module. In this case, the import statement may be executed many times.
Apart from stylistic issues, what is the performance cost of doing this?
There's very little cost to a repeated import statement, since Python caches modules and only imports them once (at the first import ), unless explicitly asked to reload a module with the reload function.
If multiple modules imports the same module then angular evaluates it only once (When it encounters the module first time). It follows this condition even the module appears at any level in a hierarchy of imported NgModules.
The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.
When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.
There's very little cost to a repeated import
statement, since Python caches modules and only imports them once (at the first import
), unless explicitly asked to reload a module with the reload
function. The effect (and rough performance impact) of a repeated import
statement is essentially just binding the imported names in the local namespace.
It isn't completely free, however; import
does have to lock and unlock the import table lock, and resolve the provided names. This means that can still slow down your program if called frequently.
Take a look at the explanation on this site:
https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead
Even though Python won't import the same module multiple times, you may still have a performance hit depending on how your code is structured. You may be able to use the Timer to see what the actual impact is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With