User guide

206 Memory Management
void f(void) {
int temp;
temp = b * c * 4;
d = (a * 2) + temp;
e = a - temp;
}
Another form of common sub-expressions that might not be as obvious occurs
with array indexing. Consider the following Before-and-After example that
demonstrates the value in avoiding repeated indexing into an array element. Not
only is there an obvious code savings by using a temporary pointer variable, there
is a simplification of the code as well (the Before example contains three
multiplies, one for each access to the array, whereas the After example only
contains one multiply operation).
Before (compiles to 46 bytes of code):
struct s {
int x, y, z;
} a[5];
void f(int i) {
a[i+2].x = 3;
a[i+2].y = 5;
a[i+2].z = 7;
}
After (compiles to 33 bytes of code):
struct s {
int x, y, z;
} a[5];
void f(int i) {
struct s *p;
p = &(a[i+2]);
p->x = 3;
p->y = 5;
p->z = 7;
}
Use Function Calls Liberally
Because function calls are relatively cheap in terms of the code space and
execution time overhead, replacing even a single line of complex code with an
equivalent function can reduce code space if that line of code is used two or more
times in a program. Some lines of code involving network variables might not
look complex, but the underlying operations could be.
For example, consider the increment of an element in a structure which is part of
an array of network variables; this operation generates a considerable amount of
code. Replacing two such occurrences with a single function call saves code space
at the expense of a minor performance penalty.
Also, consider passing expressions and values as function actual parameters,
rather than using global variables. Accesses to parameters are generally more
efficient than (or are no worse than) accesses to globals.