2

I am support a legacy application where I see code like this:

'Use Session for everything?
If Session("UserType") = "Admin" Then
    'do admin something
ElseIf Session("UserType") = "Manager" Then
    'do manager stuff
ElseIf Session("UserType") = "User" Then
    'do regular stuff
Else
    'do anonymous stuff
End If

Would declaring a local variable, assigning the session variable to the local variable, then using the local variable for tests be faster and better for performance?

'Use local variable?
Dim UT As String = Session("UserType")
If UT = "Admin" Then
    'do admin something
ElseIf UT = "Manager" Then
    'do manager stuff
ElseIf UT = "User" Then
    'do regular stuff
Else
    'do anonymous stuff
End If

Or does IIS automatically cache the Session variable value once it retrieves it for the current executing code?

DWRoelands
  • 4,878
  • 4
  • 29
  • 42
J Hays
  • 153
  • 9

1 Answers1

0

From HttpApplication.PostAcquireRequestState Event we can see that an event is raised when the session state has been acquired:

Occurs when the request state (for example, session state) that is associated with the current request has been obtained.

ASP.NET Session State Overview states:

Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object.

Putting those together, we can deduce that session values are not extracted from the request every time you use them, which appears to be your concern. Calling it caching may be pushing the idea of caching a bit too far.

It is not IIS handling all that: it is ASP.NET.

Regarding the code you showed, personally I would prefer to see that handled with a Select Case, but it's up to you.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84