Transient Variable in Salesforce

Transient keyword to declare instance variable that can not be saved and should not transmitted as part of view state for visual force page. This helps us reducing the view state of visualforce page. As we all know that, there is a limit of 135KB of viewstate and many times this Transient keyword helps us to reduce the view state.

In below example I have created two Datetime variable, one is with transient keyword and another one is without transient keyword and populating value with both variables. I used Refresh button to refresh the Visualforce page, however only Datetime dt2 variable will change, because of this is declare as transient.

Controller:

public class SampleController {
    DateTime dt1;
    transient DateTime dt2;
    
    public String getDT1() {
        if (dt1 == null) dt1 = System.Now();
        return '' + dt1;
    }
    
    public String getDT2() {
        if (dt2 == null) dt2 = System.Now();
        return '' + dt2;
    }
}

Visualforce Page:

<apex:page controller="SampleController">
    Datetime 1: {!dt1} <br/>
    Datetime 2: {!dt2} <br/>
    <apex:form >
        <apex:commandLink value="Refresh"/>
    </apex:form>
</apex:page>