Skip to content

Perf: Cache reflection metadata in MiniJwtService#23

Merged
jeanlrnt merged 3 commits intomainfrom
copilot/implement-reflection-caching
Dec 22, 2025
Merged

Perf: Cache reflection metadata in MiniJwtService#23
jeanlrnt merged 3 commits intomainfrom
copilot/implement-reflection-caching

Conversation

Copy link
Contributor

Copilot AI commented Dec 22, 2025

Implement Reflection Caching in MiniJwtService ✅

Performance optimization to cache reflection metadata for types used in JWT token generation and deserialization.

Completed Tasks:

  • Add a static ConcurrentDictionary to cache property metadata for each type
  • Create a helper method to get or compute cached property metadata
  • Update GenerateToken<T> to use the cache instead of direct reflection
  • Update ValidateAndDeserialize<T> to use the cache instead of direct reflection
  • Add unit tests to verify caching behavior
  • Run existing tests to ensure no regression
  • Build and verify the solution
  • Code review completed with no issues
  • Security scan completed with no vulnerabilities
  • Fix CI failure - removed flaky performance test

Summary:

Successfully implemented reflection caching in MiniJwtService to eliminate repeated reflection operations. The cache uses a thread-safe ConcurrentDictionary<Type, PropertyClaimInfo[]> to store property metadata for each type.

Changes:

  • Modified MiniJwtService.cs with minimal surgical changes
  • Added 2 functional unit tests in MiniJwtTests.ReflectionCache.cs
  • Removed flaky performance test that was causing CI failures
  • All 27 tests pass (25 existing + 2 new)
  • No breaking changes, fully backward compatible
Original prompt

This section details on the original issue you should resolve

<issue_title>Perf: Implémenter un cache pour la réflexion (Reflection Caching) dans MiniJwtService</issue_title>
<issue_description>Actuellement, les méthodes GenerateToken et ValidateAndDeserialize utilisent la réflexion (Reflection) à chaque appel pour inspecter les propriétés de l'objet payload et récupérer les attributs [MiniJwtClaim].
Ceci est visible dans MiniJwtService.cs :
• Ligne 391 : var props = typeof(T).GetProperties(...) 
• Ligne 392 : prop.GetCustomAttribute() 
• Ligne 412 : Même logique pour la désérialisation 
Problème :
La réflexion est une opération coûteuse en CPU. [cite_start]Dans des scénarios à fort trafic ou dans des boucles (comme démontré dans l'exemple WorkerService [cite: 298-299]), répéter cette analyse de type à chaque génération de token est inefficace, car la structure des classes Payload ne change pas pendant l'exécution de l'application.
Solution proposée :
Introduire un mécanisme de mise en cache statique (thread-safe) pour stocker les métadonnées des types analysés une seule fois.

  1. Ajouter un champ statique : ConcurrentDictionary<Type, List<(PropertyInfo Prop, string ClaimType)>>.
  2. Créer une méthode privée GetTypeMetadata() qui :
    • Vérifie si le type est dans le cache.
    • Si non, effectue la réflexion (GetProperties + GetCustomAttribute), construit la liste de mapping, et la stocke.
    • Retourne la liste mise en cache.
  3. Mettre à jour GenerateToken et ValidateAndDeserialize pour utiliser ce cache au lieu d'appeler GetProperties directement.
    Avantages :
    • Réduction significative de l'allocation mémoire et du temps CPU par appel.
    • Aucun Breaking Change : l'API publique reste identique.
    Tâches :
    • [ ] Ajouter ConcurrentDictionary dans MiniJwtService.
    • [ ] Implémenter la logique de récupération/stockage des métadonnées (PropertyInfo + ClaimType).
    • [ ] Refactoriser GenerateToken pour utiliser le cache.
    • [ ] Refactoriser ValidateAndDeserialize pour utiliser le cache.
    • [ ] Vérifier que les tests unitaires passent toujours.</issue_description>

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

…lize methods

Co-authored-by: jeanlrnt <63308635+jeanlrnt@users.noreply.github.com>
Copilot AI changed the title [WIP] Implement caching for reflection in MiniJwtService Perf: Cache reflection metadata in MiniJwtService Dec 22, 2025
Copilot AI requested a review from jeanlrnt December 22, 2025 15:21
@jeanlrnt
Copy link
Owner

@copilot an error occurs in the ci, fix it in this pull request:

Second batch took significantly longer (4ms) than first batch (1ms), suggesting cache may not be working

Co-authored-by: jeanlrnt <63308635+jeanlrnt@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Dec 22, 2025

@copilot an error occurs in the ci, fix it in this pull request:

Second batch took significantly longer (4ms) than first batch (1ms), suggesting cache may not be working

Fixed in commit a1f75dd. Removed the flaky performance test that was causing CI failures. The test was timing-dependent and unreliable in CI environments. The remaining two functional tests properly verify that the reflection caching works correctly.

@jeanlrnt jeanlrnt marked this pull request as ready for review December 22, 2025 16:46
Copilot AI review requested due to automatic review settings December 22, 2025 16:46
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR implements a performance optimization by introducing reflection caching in MiniJwtService to eliminate repeated reflection operations during JWT token generation and validation. The cache stores property metadata for each type using a thread-safe ConcurrentDictionary.

Key Changes:

  • Added a static reflection cache to store property/claim mappings per type
  • Refactored GenerateToken<T> and ValidateAndDeserialize<T> to use cached metadata
  • Added functional tests to verify the caching implementation works correctly

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/MiniJwt.Core/Services/MiniJwtService.cs Implements reflection caching with ConcurrentDictionary<Type, PropertyClaimInfo[]>, adds PropertyClaimInfo nested class, and GetOrComputePropertyClaimInfos helper method; refactors token generation and deserialization to use cached metadata
src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs Adds two functional tests verifying that token generation and deserialization work correctly with the caching implementation for single and multiple types

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@jeanlrnt jeanlrnt changed the base branch from main to develop December 22, 2025 17:08
@jeanlrnt jeanlrnt changed the base branch from develop to main December 22, 2025 17:09
@jeanlrnt jeanlrnt merged commit 4f32dff into main Dec 22, 2025
21 checks passed
@jeanlrnt jeanlrnt deleted the copilot/implement-reflection-caching branch December 22, 2025 17:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Perf: Implémenter un cache pour la réflexion (Reflection Caching) dans MiniJwtService

2 participants

Comments