Using the transient Keyword

Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view state for a Visualforce page. For example:

1Transient Integer currentTotal;
You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These objects include the following:
  • PageReferences
  • XmlStream classes
  • Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as a collection of Savepoints
  • Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
  • JSONParser class instances.
Static variables also don't get transmitted through the view state.
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date continues to have its original value, which has been deserialized from the view state, so it remains the same.
1<apex:page controller="ExampleController">
2  T1: {!t1} <br/>
3  T2: {!t2} <br/>
4  <apex:form>
5    <apex:commandLink value="refresh"/>
6  </apex:form>
7</apex:page>
01public class ExampleController {
02
03    DateTime t1;
04    transient DateTime t2;
05
06    public String getT1() {
07        if (t1 == null) t1 = System.now();
08        return '' + t1;
09    }
10
11    public String getT2() {
12        if (t2 == null) t2 = System.now();
13        return '' + t2;
14    }
15}

Counters