Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async is slow due to isawaitable use #1514

Closed
mohd-akram opened this issue Oct 16, 2021 · 3 comments · Fixed by #1516
Closed

Async is slow due to isawaitable use #1514

mohd-akram opened this issue Oct 16, 2021 · 3 comments · Fixed by #1516
Milestone

Comments

@mohd-akram
Copy link
Contributor

I was benchmarking a render and I noticed that the use of inspect.isawaitable really slows things down:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    22920    0.024    0.000    0.059    0.000 .../python3.10/inspect.py:348(isawaitable)

Almost 60 milliseconds is spent there, more than any other Python builtin in the profile.

Environment:

  • Python version: 3.10
  • Jinja version: 3.0.1
@davidism
Copy link
Member

Sounds like something that should be reported to CPython so they can improve its performance. I don't see what Jinja could do about this.

@mohd-akram
Copy link
Contributor Author

I'm getting anywhere between 15% to 2x improvement with this change:

primitives = {int, float, bool, str, list, dict, tuple}

async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
    if type(value) in primitives:
        return t.cast("V", value)

    if inspect.isawaitable(value):
        return await t.cast("t.Awaitable[V]", value)

    return t.cast("V", value)

Since most objects are primitives, we can avoid a costly check.

@davidism
Copy link
Member

Happy to review a PR.

@davidism davidism added this to the 3.0.3 milestone Nov 9, 2021
@davidism davidism closed this as completed Nov 9, 2021
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 24, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants