BASIC Efficiency Tips
From Bitchin100 DocGarden
Revision as of 12:56, 28 June 2009 by Ronw
(From a Letter in Portable 100, Richard Horowitz):
- All variables should be typed at the beginning of the program. Use DEFINT, DEFSNG, etc. Even string variables should be typed because the "$" used with each such variable takes a byte of storage.
- Use integers wherever possible, especially in counting loops. The time savings is dramatic. Integers are 2 1/2 times faster than the default of double precision.
- Eliminate the variable argument on the NEXT portion of For-Next loops. Here is a real kicker. Besides the savings of one byte of storage for each such occurrence, integers are 60 percent slower, reals are 50 percent slower, and double precision is 80 percent slower when you specify the variable than when you simply specify NEXT.
- Eliminate final quote marks on all literals that appear at the end of lines. A byte is saved for each.
- Use as many multiple statements per line as you can since for each line number eliminated, you have a net savings of four bytes (the five needed for each separate line less the one byte used for each ":").
- Eliminate spaces. Your archival copy should have them for intelligibility, but your running copy will save one byte for each space that is removed.
- Put all initialization code at the end of your program and do a GOTO to a GOSUB. Little used routines at the end make for a dramatic improvement in speed since BASIC must search from the beginning for each line referenced.
- Put all time critical code at the beginning of the program for the same reason.
- Initialize all variables before you start the main body of the code. This creates a stable, linear table of variables that are accessed more rapidly. Moreover, optimize the order in which you define the variables so that the most frequently referenced variable is the first to be defined, the second most frequently referenced variable is the second to be defined, and so on. Thus when the BASIC interpreter encounters a previously defined variable, the time it consumes to find said variable among the linear table of variables will be comensurate with the importance (i.e., frequency of reference) of the variable and consequently BASIC program interpretation time is optimally short.
- Do not use the supposed short-cut of raising a number to the 0.5 power to save time over the SQR routine. Inaccuracies in the 11th and 12th decimal might tend to screw up any further calculations in which you might use the result.
- Assign literals used more than once in a program to a variable. Do this in your initialization code. Almost one byte per characters is saved for each such duplication eliminated.
- Use SPACE$(X) to assign X number of spaces rather than STRING$(X,32).
- Another surprise: use REM instead of "'". This saves two bytes per occurrence. Of course you should remove all REM statements of both types from your running copy.