3

Meta Context:

I'm building an api using aiohttp. Since it's an asynchronous framework, I have to use async to define handlers. Example:

async def index_handler(request):
    return web.Response(text="Hello, world")

app = web.Application()
app.router.add_route("GET", "/", index_handler)

Code Context:

During development, I found myself in a situation where i have nested function calls like so:

def bar():
    return "Hi"

async def foo():
    return bar()

await foo()

When I was thinking about performance, I didn't know whether or not I should do these nested functions all async as well. Example:

async def bar()
    return "Hi"

async def foo():
    return await bar()

await foo()

Question:

What is the best way to do nested function calls to optimize performance? Always use async/await or always use sync? Does this makes a difference?

1
  • Processes that are naturally asynchronous should be done with async. Eg: waiting for any kind of IO. In your case it's the opposite: your "async-everywhere" solution is slower, since async does not come for free. That's another reason why every performance optimisation should come with before-after benchmarks. Commented Sep 27, 2018 at 0:38

1 Answer 1

2

Well in your case you dont need to async everything unless you have code that could potentially block things for example:

def bar():
    """This function is not async because there is no need to."""
    return "Hi"

async def foo():
    return bar()

await foo()

But if your function bar for examples sleeps or do some async functions inside, then you should async the function

async def bar():
    """This function needs to be async because there 
    are operations that potentially could block"""
    await asyncio.sleep(1)
    return "Hi"

async def foo():
    return bar()

await foo()

So for summarize, if you are using async operations you need to have a very clear idea of how your program runs and what it is doing in order to avoid to put async everywhere.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.