efficiency in django3.1
lastshusheng opened this issue · comments
It is not known whether it is asynchronous middleware or whether it will affect the efficiency of async in DJango3.1
see https://docs.djangoproject.com/en/3.1/topics/async/#performance
When running in a mode that does not match the view (e.g. an async view under WSGI, or a traditional sync view under ASGI), Django must emulate the other call style to allow your code to run. This context-switch causes a small performance penalty of around a millisecond.
This is also true of middleware. Django will attempt to minimize the number of context-switches between sync and async. If you have an ASGI server, but all your middleware and views are synchronous, it will switch just once, before it enters the middleware stack.
I was puzzled by @adamchainz's answer, so I did my own research.
Question 1: It is an asynchronous middleware?
CorsMiddleware
inherits from MiddlewareMixin
which sets async_capable
to True
.
So yes, CorsMiddleware
is an asynchronous middleware.
Question 2: Does it affect the performance of async views?
The documentation says, "If your middleware has both sync_capable = True
and async_capable = True
, then Django will pass it the request without converting it.".
So no, CorsMiddleware
doesn't affect the performance of async views.
It does affect the performance, because the async capability built-in by MiddlewareMixin
passes from async to sync and back again.
I'd like to convert this middleware to support asynchronous requests natively, but I think we should wait until the middleware in Django all have their own native async implementations rather than using MiddlewareMixin
.