I have these extension methods below, 2 from ClaimsPrincipal and one from UserManager, all fetch email.
What is the difference and which one is faster? (i.e. doesn't require as much time to fetch from the database or doesn't fetch from the database at all or do they all fetch from the db?
var email = HttpContext.User.GetUserEmail();
public static string GetUserEmail(this ClaimsPrincipal user) {
return user.FindFirst(ClaimTypes.Email)?.Value;
}
var email = HttpContext.User.RetrieveEmailFromPrincipal();
public static string RetrieveEmailFromPrincipal(this ClaimsPrincipal user) {
return user?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
}
var ca = await _userManager.Users
.Where(p => p.Id == d)
.Select(p => p.Email)
.FirstOrDefaultAsync();
GetUserEmail()
and RetrieveEmailFromPrincipal()
are extension methods for ClaimsPrincipal
objects. They are retrieving the user's email address from the claims. If you check the implementation FindFirst()
you will find that it uses the same foreach
loop for iteration as FirstOrDefault()
. The difference between the two is mostly stylistic and there is no significant difference in performance between them.
The time complexity of these two methods would be very similar. They both have to scan through the list of claims for the user until they find a claim of the required type.
The third approach retrieves the user's email address from the database using Entity Framework.
Usually, the extension methods on ClaimsPrincipal
would be faster, because the claims are already in memory (retrieved during the authentication process) and there's no need to make a round trip to the database. However, they require that the email claim has already been added to the user's claims, which might not always be the case, depending on how your application is set up.
Please read the article for details about fetching user data How to get the current logged in user ID in ASP.NET Core?