Skip to content

from ... import ... has a significant performance overhead #132310

@Dreamsorcerer

Description

@Dreamsorcerer

Bug report

Maybe there's some fundamental reason I'm not aware of, but using the from syntax when importing creates variables which are typically over 4x slower to reference for some reason.

Expected behaviour

I'd expect these 2 versions of code to produce basically the same result functionally and performance-wise:

from random import sample
import random
sample = random.sample
del random

Actual results

The first one is over 5x slower to reference:

> python3 -m timeit 'from random import sample' 'sample'
500000 loops, best of 5: 823 nsec per loop
> python3 -m timeit 'import random' 'random.sample'
2000000 loops, best of 5: 161 nsec per loop
> python3 -m timeit 'import random; sample = random.sample' 'sample'
2000000 loops, best of 5: 161 nsec per loop

CPython versions tested on:

3.9 and 3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions