The main difference between the two (static
versus transient
) is that static
variables exist only once per transaction, but transient
variables can exist many times. In other words, static
variables have a global scope, while transient
variables have a local scope. In many examples you've likely seen, you've probably only seen these variables used at the top level of a class, and the behavior seems identical (because in that case, they are functionally equivalent).
Let's take a look at a less-published variety of the use of transient
:
public class Controller {
public class Wrapper {
public transient Integer transientRowNumber { get; set; }
public Integer normalRowNumber { get; set; }
}
public Wrapper[] items { get; set; }
public Controller() {
items = new Wrapper[0];
for(Integer i = 0; i < 10; i++) {
Wrapper temp = new Wrapper();
temp.transientRowNumber = temp.normalRowNumber = i;
items.add(temp);
}
}
}
<apex:page controller="Controller">
<apex:form>
<table>
<thead>
<tr>
<th>
Transient
</th>
<th>
Non-Transient
</th>
</tr>
</thead>
<tbody>
<apex:repeat value="{!items}" var="item">
<tr>
<td>
{!item.transientRowNumber}
</td>
<td>
{!item.normalRowNumber}
</td>
</tr>
</apex:repeat>
</tbody>
</table>
<apex:commandButton value="Refresh" />
</apex:form>
</apex:page>
In this code, you'll see the values loaded initially, but when you click the button, the left column will be cleared out. We did not store that column in our view state, so on the next round-trip to the server, those values do not persist. This is something you can't do with static variables, as only one static variable can exist at a time, and you can't put static variables inside an inner class.
This usage is rarer, but it might be helpful to know for certain kinds of algorithms, especially when you start using "wrapper" classes to organize data for display in a Visualforce page.