Skip to content
Advertisement

Performance impact in having a single import per line

does anybody know if there is a performance difference between having all imports from one module in a single line vs one per line. For example, having:

JavaScript

instead of:

JavaScript

I’m trying to convince my team to use reorder-python-imports in our pre-commit hooks and this doubt is the only obstacle that prevents me from adding it.

Advertisement

Answer

Combining imports is technically faster but there should not be a noticeable performance difference in real world usage. Python modules execute only once, on their first time being imported. After being initialized, you only incur the negligible cost of the additional import statements themselves.

As long as you only do top-level imports, your imports will only ever execute during startup anyway. By combining them you might at best manage to shave off a negligible amount of milliseconds during startup. Read the Python docs on the import mechanism.

Here is my machine’s performance after a million repetitions each:

test1.py

JavaScript

test2.py

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement