ASP.NET Profiles were introduced to assist developers in persisting user information. Previous methods of persistence all had limitations in how they stored user data, Session state would only be held in memory and lost once the user’s session ended, a query-string would only be useful for that particular page and had to be recreated on each new page, cookies are only available on a single user machine. Profiles addressed all these difficulties by providing a simple persistent store which plugs into ASP.NET Membership. Profiles are ideal for storing user info such as preferences for a web app, besides being convenient they are very simple to use – just create them in the web.config file and access them anywhere in the application using
But with the convenience and power of Profiles comes a price – performance. Profiles are stored in a database, and therefore if used without caution can have a major performance cost.
To understand how best to use Profiles, first we will look at how they work under the hood. Profiles plug into the life-cycle of the page at two points:
- The first time the Profile object is accessed in your code ASP.NET retrieves all the profile data for the current user from the database. If the profile data is used more than once in the same request ASP.NET reads it only once and then reuses it.
- If profile data is updated, that update is deferred until the page has finished processing( ie after the PreRender, PreRenderComplete, and Unload events have completed). At that point the profile data is written to the database, thus multiple changes are updated in batch.
Thus, using Profiles can result in an extra two database hits per request (if Profile data is read and then updated) or one extra database hit (for simply reading the Profile data). It should be noted that Profiles do not have a caching mechanism so so every request for Profile data or update of Profile data requires a database connection.
Thus from a performance viewpoint, Profiles are best when:
- There are a relatively small number of pages which access the Profile data.
- Profiles only store small amounts of data (since accessing Profiles always results in the retrieval of all the Profile data for that user it can be quite result in large payloads).
Therefore to optimize performance when using ASP.NET Profiles it is best to combine
Profiles with other methods of state management. For example, a web app could first check if there was a cookie stored on the user’s machine for the user’s date format preference and if not available this data could be retrieved from the Profile (which would then then add a cookie) this will save a database round trip each time to check the preferences (session state could also be used for this).