In so many interviews this question will be asked. Generally people will read order of execution of record saving, but they will miss this. You shouldn’t be one of them. So read below.
Mainly Visualforce Page Execution in two scenarios.
- Order of Execution for Visualforce Page Get Requests
- Order of Execution for Visualforce Page Post back Requests
However HTTP is a stateless protocol, In Visualforce, page state is persisted as a hidden form field that is automatically inserted into a form when the page gets generated. We call this the view state of the page. The view state captures the state of the page and state of its associated controllers and extensions and the component tree on the page. The view state is posted back along with the other form data, which gives the server enough information to recreate the page state to which new changes can be applied.
What is contained in the View State?
- The data in the view state should be sufficient to recreate the state of the page when the post back is received. To do this, it stores the following data:
- All non-transient data members in the associated controller (either standard or custom) and the controller extensions.
- Objects that are reachable from a non-transient data member in a controller or controller extension.
- The component tree for that page, which represents the page’s component structure and the associated state, which are the values applied to those components.
- A small amount of data for Visualforce to do housekeeping.
Best Practices for Optimizing View State:
- Minimize Number of Forms on a Page
- Assume a page contains two forms – form 1 and form 2. Whichever form the user submits and causes a post back, the view state for the page needs to get transferred. To support this, each form on your page will have its own copy of view state. If the associated view state is large, instead of having multiple forms on a page, have a single form and use <apex:actionRegion> to submit portions of the form. This practice will ensure that only a single copy of the view state is associated with that page.
- Declare Variables as Transient to Reduce View State.
- Use Custom Objects or Custom Settings to Store Large Quantities of Read-Only Data.
- 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.
EX: Transient DateTime currentDateTime;
During a post back request, the view state is decoded and used as the basis for updating the values on the page.
Note: A component with the immediate attribute set to true bypasses this phase of the request.