Hints for Smaller Code - mhightower83/Arduino-ESP8266-misc GitHub Wiki
Hints for Smaller Code
Inspired by Earle F. Philhower, III's PR
Use int variables instead of byte variables.
Use int instead of char, uint8_t, etc for byte-oriented types.
Where it doesn't make a functional difference, make global variables
ints and not uint8_t. Bytewide updates and extracts require multiple
instructions and hence increase code size as well as runtime.
Or unsigned for uint8_t and char (char on ESP8266 is unsigned) instead of int if the sitiation calls for it.
Make local flag vars int
Make short functions inline
Check if inlining short functions save iRAM. Certain conditions can be statically evaluated by GCC. There is also a cost of saving locals before the call is made.
Convert state machine to 1-hot for faster lookup
GCC won't use a lookup table for some switch statements, so it ends up using a series of straight-line compare-jump, compare-jumps to figure out which branch of code to execute for each state. For branches that have multiple states that call them, this can expand to a lot of code.
Short-circuit the whole thing by converting the FSM to a 1-hot encoding while executing it, and then just and-ing the 1-hot state with the bitmask of states with the same code.
Use a struct to hold globals
Move all global objects into a struct. This lets a single base pointer register to be used in place of constantly reloading the address of each individual variable.
Moving to a C++ implementation based on a class object might be an alternative.
Use enums instead of #define
Use enums instead of #define, in the hope that it will
allow GCC to more easily flag problems and general good code
organization.
Save space by reordering structures
Group like types together such that the structure is naturally packed.