Loop Invariants
When you initialize a tuple in a loop, some attributes might be invariant.
Here is an example of moving part of a tuple's initialization out of a
loop:
type tupleType = int32 invary, int32 vary;
type listOfTuples = list<tupleType>;
void createListOfTuples (mutable listOfTuples a,int32 start, int32 n) {
mutable int32 i = 0;
while (i < n) {
appendM(a, {invary = n, vary = start + i} );
++i;
}
}In the example, a new tuple is created and initialized for each iteration of the loop. Notice
that only the
vary attribute changes in the loop. So instead of creating the
tuple in the loop, you can create it outside of the loop. Then, for each iteration of the loop
you can set the vary attribute as follows:
void createListOfTuples (mutable listOfTuples a,int32 start, int32 n) {
mutable int32 i = 0;
mutable tupleType t = {invary = n, vary = 0};
while (i < n) {
t.vary = start + i;
appendM(a,t);
++i;
}
}This technique saves the creation and part of the initialization of the tuple for
each loop iteration. Similar techniques can be used when you submit tuples from an
operator.