In this post I want to highlight the difference between two methods for returning Sitecore users.
var getAllUsers = UserManager.GetUsers()
And
var getAllUsersByDomain = Domain.GetDomain("extranet").GetUsers(); // or Sitecore.Context.Domain.GetUsers()
In some cases the 2 methods above may be used interchangeably but I believe you should probably look at using the second method in order to future proof your Sitecore solution for a handful of reasons.
If you are working with a single Sitecore website then you are probably only dealing with a single extranet domain (ex: Extranet). But what happens when you introduce a second website and second domain into the solution? And what happens if you start using the Active Directory module or the CRM connector module and you suddenly have thousands and thousands of extra users? This is when things will start to go wrong.
First off, you may end up getting functionality that you did not expect if you are returning all users instead of just the users for the specific domain you were working with.
Second, your code can become extremely slow if you are returning ALL users and then filtering them based on domain instead of using the proper method to only return the users you need. And when I say there are performance implications I mean there can be some serious performance issues.
In the simple example below I have a total of 17,000 users in Sitecore. However my target domain only contains 120 users. So the example below shows the performance implications of returning all 17,000 users and filtering through them instead of only returning the users for the target domain.
I used the Stopwatch class in C# to help estimate the time it takes for each scenario. Admittedly the Stopwatch isn’t perfect but it was able to give us some rough numbers.
var stopwatch1 = new Stopwatch(); stopwatch1.Start(); var domainUserList = Domain.GetDomain("customdomain").GetUsers(); stopwatch1.Stop(); var stopwatch2 = new Stopwatch(); stopwatch2.Start(); var getAllUsers = UserManager.GetUsers(); var allUsersFilteredByDomain = getAllUsers.Where(user => user.Domain.Name == "customdomain").ToList(); stopwatch2.Stop(); Response.Write("<br>Target Domain Users Only - " + domainUserList.Count() + " Users - Time elapsed: " + stopwatch1.Elapsed + "<br><br>"); Response.Write("Filter Through All Users - " + allUsersFilteredByDomain.Count() + " Users - Time elapsed: " + stopwatch2.Elapsed + "<br>");
Yikes, what a difference! In each case we returned 120 users but we’re talking about a fraction of a second compared to well over 10 seconds. And this will continue to get slower as more and more users are added to Sitecore. Note that the GetUsers method is not actually the main slow down but it’s the filtering of users by domain after you have the full set of users returned.
Odds are that people will make this mistake solely because they don’t know that you can grab users by domain so let’s all help spread the word!
Leave a Reply