guido@boring.UUCP (08/17/85)
(I hope this topic is OK in this group -- it concerns programming in general,
not languages in general, but I can't think of a better place to post.)
I know quite a lot of techniques to make programs faster. Often it's a
question of choosing the right algorithm depending on the use that's
going to be made of it. You usually end up with more code (e.g.,
quicksort is larger than straight insertion).
I also know a few techniques of making code smaller (besides using a
space-optimizing compiler -- assume I can't change the compiler).
For instance, turning code sequences that occur frequently into subroutines
might save space -- but the routine call costs space, too, and maybe
you have to pass ten local variables as parameters. Reorganizing a
program completely after it's been hacked up for a (too) long time often
helps. I believe that the data structures chosen can make a lot of
difference, even if they don't differ in the order of the algorithm used.
One technique that I have considered is the following:
Assume that we have a large switch where we call lots of routines.
switch (type) {
case 0: foo(a1, a2); break;
case 1: bar(a1, a2); break;
case 2: snafu(a1, a2, a3); break;
...
}
If there is enough regularity in it, and many cases, I believe this
can be sped up by having a table of routines, since then the calling
sequence has to be generated only once:
int (*table[]) = {foo, bar, snafu, ...};
...
if ("type is alright")
(*table[type])(a1, a2, a3);
(Originally this way of switching may have be rejected because
the number of cases was small and the cases weren't contiguous;
after adding more cases to the switch the problem becomes clear.
For really scattered cases the table-of-functions techniques
can be augmented by a look-up of the key.)
This may be typical of the techniques employed in general: replacing a
flexible, easy-to-use technique by something less general which just
does the job in this particular case. It does require a rich language:
the above example could not be coded in Pascal.
Note that I don't care about the size of my source code (well, I do, but
that's not the point of this question). It's the size of the object code
(less the data's) that most interests me here.
Let us hear of your favourite trick to chop down your code!
Guido van Rossum, CWI, Amsterdam (guido@mcvax)