Avoid repeated method calls within an algorithm

Calling a method repeatedly to obtain a value often results in poor performance. As a performance best practice, Guidewire recommends that you save the value from the first method call in a local variable. Then, use the local variable to repeatedly test the value.

The following sample Gosu code suffers a performance problem. It calls a performance intensive method twice to test which value the method returns.

if (policy.expensiveMethod() == "first possibility") {  // first expensive call
  // do something
} 

 else if (policy.expensiveMethod() == "second possibility") {  // second expensive call
  // do something else
}

The following modified sample code improves performance. It calls a performance intensive method once and saves the value in a local variable. It then uses the variable twice to test which value the method returns.

var expensiveValue = policy.expensiveMethod()  // Save the value of an expensive call.

 if (expensiveValue == "first possibility") {  // first reference to expensive result
  // do something
} 

 else if (expensiveValue == "second possibility") {  // second reference to expensive result
  // do something else
}