0
0
Djangoframework~8 mins

Receiver decorator in Django - Performance & Optimization

Choose your learning style9 modes available
Performance: Receiver decorator
MEDIUM IMPACT
This affects the event handling and signal processing speed in Django applications, impacting responsiveness during runtime.
Connecting signal handlers in Django
Django
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save)
def my_handler(sender, **kwargs):
    print('Signal received')
The receiver decorator ensures a single, clear connection to the signal, preventing duplicate calls and improving efficiency.
📈 Performance GainSingle signal connection reduces redundant processing and improves input responsiveness.
Connecting signal handlers in Django
Django
from django.db.models.signals import post_save
from django.dispatch import Signal

def my_handler(sender, **kwargs):
    print('Signal received')

post_save.connect(my_handler)
Manually connecting signals can lead to multiple connections if done repeatedly, causing duplicate handler calls and slower response.
📉 Performance CostTriggers multiple signal handler calls, increasing CPU usage and slowing interaction responsiveness.
Performance Comparison
PatternSignal ConnectionsDuplicate CallsCPU UsageVerdict
Manual connect() calls in multiple placesMultipleYesHigh[X] Bad
Using @receiver decorator once per handlerSingleNoLow[OK] Good
Rendering Pipeline
The receiver decorator registers signal handlers during app initialization, affecting how Django processes signals during runtime events.
Signal Registration
Signal Dispatch
Handler Execution
⚠️ BottleneckHandler Execution when multiple redundant handlers run
Core Web Vital Affected
INP
This affects the event handling and signal processing speed in Django applications, impacting responsiveness during runtime.
Optimization Tips
1Use @receiver decorator to connect signals once and avoid duplicates.
2Avoid manual signal connections scattered across code to prevent multiple handler calls.
3Efficient signal handling improves input responsiveness (INP) in Django apps.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance benefit of using the @receiver decorator in Django?
AIt reduces the size of static files.
BIt automatically caches database queries.
CIt prevents multiple signal connections and duplicate handler calls.
DIt speeds up template rendering.
DevTools: Django Debug Toolbar
How to check: Enable the signals panel in Django Debug Toolbar and trigger the event; observe how many times the handler runs.
What to look for: Multiple handler calls indicate redundant connections; a single call confirms efficient signal handling.