Next Previous Contents

8. Register variables

The runtime for all supported platforms has 6 bytes of zero page space available for register variables (this could be increased, but I think it's a good value). So you can declare register variables up to a total size of 6 per function. The compiler will allocate register space on a "first come, first served" base and convert any register declarations that exceed the available register space silently to auto. Parameters can also be declared as register, this will in fact give slightly shorter code than using a register variable.

Since a function must save the current values of the registers on entry and restore them on exit, there is an overhead associated with register variables, and this overhead is quite high (about 20 bytes per variable). This means that just declaring anything as register is not a good idea.

The best use for register variables are pointers, especially those that point to structures. The magic number here is about 3 uses of a struct field: If the function contains this number or even more, the generated code will be usually shorter and faster when using a register variable for the struct pointer. The reason for this is that the register variable can in many cases be used as a pointer directly. Having a pointer in an auto variable means that this pointer must first be copied into a zero page location, before it can be dereferenced.

Second best use for register variables are counters. However, there is not much difference in the code generated for counters, so you will need at least 100 operations on this variable (for example in a loop) to make it worth the trouble. The only savings you get here are by the use of a zero page variable instead of one on the stack or in the data segment.

Register variables must be explicitly enabled, either by using -Or or --register-vars on the command line or by use of #pragma register-vars. Register variables are only accepted on function top level, register variables declared in interior blocks are silently converted to auto. With register variables disabled, all variables declared as register are actually auto variables.

Please take care when using register variables: While they are helpful and can lead to a tremendous speedup when used correctly, improper usage will cause bloated code and a slowdown.


Next Previous Contents