Understanding and Monitoring Visualforce View State

What is View State?

Since HTTP is a stateless protocol, any web application that needs to maintain state between page requests has to deal with how to handle View State. Visualforce handles it by using a hidden form element. Data in components and controllers are stored in an encrypted and hidden field on your page (see image below) that must be serialized and deserialized every time the Visualforce page is requested. Large view state sizes can quickly cause pages to suffer performance problems. Additionally, the Force.com platform limits your pages to a maximum view state size of 135Kb.

Like this Post? Then you will really like the “Improving Visualforce Performance” course that I designed for lynda.com. It was based on this post specifically and goes into great detail about each one of the tips in this post. Check it out!

ViewStatePNG

When is View State needed?

I have seen many examples of code on the forums and in blog posts that use the form tag, even though it is really not needed. I imagine this can happen when people copy code snippets and then change them to fit their needs. Beginning developers will likely not realize the potential negative impact that can occur by leaving in a form tag that is not necessary.

If your Visualforce page includes an <apex:form> component, then it is using View State and could suffer performance problems.

Form tags are only needed when the Visualforce page collects input from the user and is required when using certain apex components such as inputField, commandButton, and any of the action tags. However, it is not needed when just displaying output to users, which many Visualforce pages do. So, the first thing you should always ask is, “Is the form tag in my Visualforce page really needed?” If you are not sure, remove it and try saving the page. If another component requires the form tag, then you will get a compile error telling you this.

How to monitor View State

If your page does require a form tag, then you should be aware of how much view state your page is consuming. To monitor view state, you must first enable this by going to My Settings | Personal | Advanced User Details and clicking Edit. Select the Development Mode AND Show View State in Development Mode checkboxes and click Save.

To access the Development mode footer, navigate to a Visualforce page in your browser by replacing the last characters of the url with /apex/PageName. For example, if you have created a page named AccountSearch and your Salesforce Instance is na3.salesforce.com, then the URL should look like this:

https://na3.salesforce.com/apex/AccountSearch

When you do this, a Development mode footer will appear at the bottom of the page and if your page has a form tag, then a View State tab will appear (such as in the image below).

Transient1

The initial view state (which means that no search has been executed yet) for this particular page is very low – only 2.64KB, which is far below the 135KB threshold allowed. But, what if this page had several more apex components, or what if I executed a search returned hundreds or thousands of records? Well, that number could go up rather quickly and this is why you need to be aware of what your pages view state is and to test it against large quantities of data.

How can I lower View State?

If you do find yourself in the position where your page is performing poorly due to view state (or even encountering limit errors), then there are a few things you can do to fix this. If you have to use a form tag, then the first thing you can do is examine your View State using the Development mode footer and determine whether any of your variables can be marked as transient.

The Transient keyword can be used to flag a variable so that it does not get saved to view state. Chances are, all the variables in your page do not need to be saved between page requests and so this is the easiest and fastest way to lower your view state.

For example, take a look at the markup code below which is used to render a simple Account Search form:

<apex:page standardController="Account" extensions="AccountSearchController">  
  <apex:form >  
      <apex:pageBlock title="Search Result">  
          <apex:pageBlockButtons location="top">
              <apex:inputText value="{!searchstring}" label="Input"/>    
              <apex:commandButton value="Search Accounts" action="{!search}"/>  
          </apex:pageBlockButtons>   
          <apex:pageblockTable value="{!acc}" var="a">  
              <apex:column headerValue="Name">  
                  <apex:outputlink value="/{!a.id}">{!a.Name}</apex:outputlink>  
              </apex:column>  
              <apex:column headerValue="Account Number" value="{!a.AccountNumber}"/>  
              <apex:column headerValue="Industry" value="{!a.Industry}"/>  
              <apex:column headerValue="Phone" value="{!a.Phone}"/>  
              <apex:column headerValue="Website" value="{!a.Website}"/>  
          </apex:pageBlockTable>     
      </apex:pageBlock>    
  </apex:form>  
</apex:page>

and the controller look like this:

public with sharing class AccountSearchController { 
    // Matching Accounts
    public List<Account> acc {get;set;}  
    
    // Search Text entered by user
    public String searchString {get;set;}  
       
    //Constructor
    public AccountSearchController(ApexPages.StandardController controller) {  
    } 
    
    // Action method to search for Accounts  
    public void search() {  
        String searchWord = searchString + '%';  
        acc= [SELECT AccountNumber,Name,Phone,Industry,Website 
              FROM Account 
              WHERE Name like : searchWord];  
    }  
 }

The AccountSearch form is a simple search page that will accept a search string from the user and look for all accounts where the name matches. The results are returned in a variable named acc and the code, as it is now, will store all the records returned in view state. Since this search involves a wild card at the end, if the user looks for all accounts that start with the letter ‘a’ and the org has a lot of accounts, the results could be huge and the view state could easily become too large.

In this example, there are two variables (or properties) that could potentially be marked as Transient: acc and searchString. You can see then both displayed on the View State tab of the Development mode footer (see image below).

Transient

The searchString property is assigned a value when the user enters a word or phrase and clicks Search Accounts. This value is dynamically bound to a SOQL statement and the results are returned to the acc property. Since the searchString value needs to persist between the Get and Post request, it cannot be marked as Transient. But the acc property, which happens to take up the most amount of view state size in KB, contains data results that are just displayed on the page.

Once the results are returned, there is no need to store all the data in view state. The easiest way to reduce view state is to simply add the keyword Transient, so the code for the property declaration now looks like this:

// Matching Accounts
public Transient List acc {get;set;}  

Once the Transient keyword is added, you can save the page and look again at the View State tab. You should see that the acc variable has disappeared entirely and the overall view state size has decreased.

Interested in Learning More?

If you liked this post, then you might be interested in learning more about how you can improve Visualforce Performance by checking out my online course for lynda.com, “Improving Visualforce Performance“. I have an entire chapter dedicated to View State and other chapters involving the following:

  • Evaluating SOQL for efficiency
  • Using Workbench and the Query Plan tool to evaluate queries
  • Reducing use of action tags through Visualforce remoting
  • Working with the StandardSetController class
  • Using static resources

Improving Visualforce Performance – New Online Course Released

Improving Visualforce Perfomance

I am proud to announce that yesterday my online course for lynda.com, “Improving Visualforce Performance” was released. The course is a little over 2 hours long and it focuses on what you need to know to get the most out of your Visualforce performance. It is not a beginning level course (like the first one I did about Developing for Visualforce).

I based the course on a post I did over a year ago called, the “Top 5 Tips for Improving Visualforce Pages“. That post has been the most popular post on this blog for sometime, so I knew this was a good topic.

The course goes into great detail (with examples) of all the tips I covered in that original post. I spent a lot of time developing the examples and scripts for this course and I have to admit I am pretty proud of it. The 5 tips it covers include:

  1. Reducing or Eliminating View State
  2. Evaluating SOQL for Efficiency
  3. Reducing use of Action Tags
  4. Taking Advantage of the StandardSetController
  5. Incorporating Best Practices with JavaScript, HTML, CSS and Images

If you are interested, lynda.com offers a free 10 day trial that you can access here. And until Monday, August 24th, they are offering 30% off the first billing for monthly and annual subscription plans.

I would love to know what you think of the course and what recommendations you have for future course as I plan to be doing more of them.

Top 5 Tips for Improving Visualforce Pages

#1 – Reduce or eliminate view state   top5

View State is not your friend when it comes to page performance, so if you do not need it (as in your page does need to persist data between page requests), then do not use it at all. This is especially true for pages that will run on the Salesforce1 mobile platform!!!

How do you not use it all?

Do not include the <apex:form> tag unless you absolutely have to. This tag should only be used when you are accepting input from the user, so if you are only displaying data to the user, you should not have a form tag.

Like this Post? Then you will really like the “Improving Visualforce Performance” course that I designed for lynda.com. It was based on this post specifically and goes into great detail about each one of the tips in this post. Check it out!

And, even if you are accepting input, it is likely that not all the data on your page needs to be submitted through a POST request. For example, you could have a page that lists some account data, but only allows the user to change one particular field. In cases such as these, you could use the Transient keyword in the Controller class to make all the data fields (and especially collections) that are not being changed read-only. This means they will not be stored in the view state and your page will load faster.

You should also consider using JavaScript Remoting to avoid View State state by invoking the Apex Controller or Extension from JavaScript instead. This puts more load on the front-end and typically results in more code, but for certain pages that demand fast performance (especially those on the Salesforce1 mobile platform), this may be a necessary tradeoff to consider. But, if you do decide to go this route, make sure you use very efficient JavaScript code, so you do not violate Tip #5.

#2 – Evaluate SOQL for Efficiency

There are several ways you can write better SOQL code. For starters, ALWAYS make sure you place SOQL queries outside of loops. This should be done no matter what. It will not only make your page perform better, but will help avoid limit errors and should be standard practice. This also applies to DML.

Beyond that essential tip, you should also consider:

  • Only return fields that you are using on the page
  • Use WHERE clauses as much as possible to restrict the number of records returned
  • Use indexed fields in your WHERE clause as it will make the query optimizer work better. Default indexed fields are Id, Name, Owner, LastModifiedDate, and any foreign key or ExternalID fields.
  • Use the LIMIT keyword when possible
  • Use aggregation functions such as COUNT()
  • Use the WITH SHARING keyword in your controllers since the sharing architecture is used by the Query Optimizer and you will only retrieve the records that the users has access to
  • Additional suggestions (per reader JSON Hammerle) are to:
    • Use native (more selective indices) when possible
    • Hash your composite key (if you have one) into the native name field and use this hash in your WHERE clause This is comparable to a skinny table but you don’t have to work with support – and it can be delivered in a managed package.
    • Order your WHERE clause from most selective to least

#3 – Reduce use of Action tags

This kind of goes with tip #1, but since it is so important, I wanted to make it a separate point. Action tags such as <apex:ActionPoller> and <apex:ActionFunction> seem great on the surface since they are VERY easy to use, but they are memory hogs, so limit your use of them and consider alternatives.

Rather than using the ActionPoller tag, you should consider using the Streaming API. It means more code for you, but it results in no view state (remember tip #1). If you do not like the Streaming API, then consider using traditional polling using a Meta tag with a refresh and a window.location.reload.

Rather than using the ActionFunction, ActionSupport, ActionRegion tags, use Visualforce Remoting which uses no view state. Like I said earlier, it results in more code and complexity for you, but for certain pages this may be necessary. Again though, make sure you incorporate efficient JavaScript. Do NOT just copy and paste the first JavaScript snippet you find by doing a Google search.

#4 – Take Advantage of StandardSetControllers when dealing with lists of data

StandardSetControllers, which are used to create list controllers are your friends and you should use them whenever possible. The StandardSetControllers are optimized to work with large data sets of up to 10,000 records and include pagination features (which you should be using) automatically. There is no need for you to do this yourself.

When you do use them, instantiate them using a list of sObjects instead of from a query locator, as this is a more efficient way.

#5 – Incorporate Best Practices with all JavaScript, CSS and Images

No Visualforce page will perform well if it includes poorly used or inefficient HTML technologies. Make sure you incorporate best practices when including things such as Javascript, CSS and images. Things such as this:

  • Remember less is more and smaller is better.
  • Files should be minified and use Static Resources
  • Avoid using global variables
  • Place Javascript at the bottom of the page when possible and use the <script> tag and not <apex:includeScript>
  • Use browser caching when you can
  • Avoid use of iframes

There are tons of documents out there about best practices. Two of my favorites are:

https://developers.google.com/speed/docs/best-practices/rules_intro

http://developer.nokia.com/community/wiki/JavaScript_Performance_Best_Practices