Skip to content

Async is slow due to isawaitable use #1514

Closed

Description

@mohd-akram

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

Activity

  1. davidism commented on Oct 16, 2021

    @davidism
    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.

  2. mohd-akram commented on Oct 16, 2021

    @mohd-akram
    ContributorAuthor

    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.

  3. davidism commented on Oct 16, 2021

    @davidism
    Member

    Happy to review a PR.

  4. added this to the 3.0.3 milestone on Nov 9, 2021
  5. locked as resolved and limited conversation to collaborators on Nov 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions