0

I suppose this is a very simple question, but after reading a lot of documentation and tips, I still don't get the point.

Except for all external things like middleware and SGI type, if my view only consists of a database query and synchronous code to work with the received data, will using async def and sync_to_async for ORM query give me any performance boost? Since at the moment, the ORM queries are still synchronous.

async def myview(request):
    users = await sync_to_async(list)(User.objects.all())
    ...

vs

def myview(request):
    users = list(User.objects.all())
    ...

1 Answer 1

0

async/await (in general as a concept as well) does not give better performance for that particular request. What it does, is to free the main execution process to execute other code and return to it only when the operation is done.

There are 2 main cases when this increases performance:

  • in case of (intended) single threaded languages such as Python, JS, Ruby etc. An application server can run multiple requests per seconds, as it doesn't wait for external calls (DB, APIs..) while doing nothing.
  • in case your code needs to do multiple independent calls, so one does not wait for the other. For example you want to create 20 items, but the API available is only per item, so you can trigger all 20 at once using async, instead of one by one
1
  • 1
    That is, I correctly assumed that while the Django ORM is still synchronous, then there is no point in reworking simple views (consisting only of a query to the database and returning the received data in response) to async def?
    – anisimovih
    Oct 2, 2021 at 20:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.