Sunday, December 21, 2014

Where's the Visualforce viewstate coming from?

I felt inspired by a Q&A on Salesforce Stack Exchange to explore the growth of viewstates in Visualforce under different conditions. Without even reaching all of the test cases I originally set out to investigate, I was extremely surprised by my initial findings:

  • A viewstate only gets created once an apex:form is added to the page, regardless of what controller, if any, is used; but more curiously...
  • A viewstate grows when non-form elements outside the apex:form are added to the page! How? And why?


So while I wait for a response from the case that I'm going to log with Salesforce Support, I welcome anyone else's explanation for this phenomenon. Below are the Visualforce pages that support my findings above.

Visualforce viewstate exhibits
Number Title Observations
Exhibit 1 No controller, no form No viewstate
Exhibit 2 Standard Lead controller, no form No viewstate
Exhibit 3 Custom controller with persistent property, no form No viewstate
Exhibit 4 No controller, one form There's a viewstate! Which seems odd, since there's no controller to process the viewstate.
Exhibit 5 No controller, two forms There's a single viewstate that's slightly larger than what's in Exhibit 4.
Exhibit 6 No controller, two forms There's a single viewstate that's slightly larger than what's in Exhibit 5, even though literally nothing has changed except for the addition of a new p element outside of the apex:form!

I've posted the source code for the Visualforce pages to GitHub as a gist.