Avoid doubly nested loop constructs
Nesting a loop construct inside another often produces inefficient code or code that does not produce correct results. As a performance best practice, Guidewire recommends that you avoid any doubly nested loop constructs.
The following sample Gosu code attempts to find duplicate values in an array by using a for loop nested inside another. The code is inefficient because it loops through the array five times, once for each member of the array. It produces inappropriate results because it reports the duplicate value twice.
var array = new int[]{1, 2, 3, 4, 3} // An array with a duplicated value
for (y in array index m) { // Loop through the array
for (z in array index n) { // Nested loop through the array or each
// member in the outer loop
if (m != n and y == z) { // If current members in outer and inner
// loops differ and member values are equal
print("duplicate value: " + z) // Print a duplicate value in the array
}
}
}
The preceding sample code produces the following output.
duplicate value: 3
duplicate value: 3
The following sample Gosu code is a better solution. The code is more efficient because it loops through the array once only. It produces appropriate results because it reports the duplicate value once only.
var array = new int[]{1, 2, 3, 4, 3} // An array with a duplicated value
var hashSet = new java.util.HashSet() // Declare an empty hash set, which prohibits
// duplicate values
for (y in array) // Loop through the array
if (!hashSet.add(y)) { // If array value cannot be added
// to the hash set
print("duplicate value: " + y) // Print a duplicate value in the array
}
The preceding sample code produces the following output.
duplicate value: 3
