What are the best practices for optimizing the View State?

1. When using multiple forms use <apex:actionRegion> to submit portions of the form. 

2. Declare Variables as Transient to Reduce View State: An instance variable declared as transient is not saved and is not transmitted as part of the view state. If a certain field is needed only for the duration of the page request and does not need to be part of the view state, declare it as transient.

3. Recreate State versus Storing It in View State: View state should ideally contain only work in progress data (the current object being edited, multi-page wizard data, etc.) If you can reconstruct the data during postback, via a SOQL query or a web services call, do that instead of storing it in controller data members.

4. Use Custom Objects or Custom Settings to Store Large Quantities of Read-Only Data: Assume that your controller needs to call a Web service and parse a large response object. Storing it in view state may not even be an option given the size. Marking it as transient would incur the cost of an additional Web service call and parsing it again. In such instances, you could store the parsed response in a custom object and store just the record id to get to the parsed response. Custom settings provide another mechanism to cache data needed by your controller. Accessing custom settings is faster than access to custom objects since custom settings are part of your application's cache and does not require a database query to retrieve the data.

5. Refine Your SOQL to Retrieve Only the Data Needed by the Page: Only retrieve (and store) the fields you need and also filter the data to only retrieve data needed by the page.

6. Refactor Your Pages to Make Its View Stateless: Instead of using apex:commandLink or apex:commandButton components (which need to be inside a apex:form component) to invoke an action, use an apex:outputLink or other non-action method instead and implement the action through an apex:page action attribute - where it makes sense. 

Comments

Popular Posts