Storage usage of methods compared to copied code

It.... depends

A call to function involves a few things

  1. Save the context
  2. Move the parameter(s) to the appropriate registers
  3. Enter the function
  4. Execute
  5. Eventually save the return value to a register
  6. Restore the context
  7. Eventually copy the returned value to the variable

As you can see, quite a lot of things. The bold points are the ones executed also if you don't use a function.

Please note that if these functions are "methods", you have also a "hidden" parameter (the object you are applying the method onto)

So why use functions? Well, you will have to write this code in flash only once instead of more times.

What is best? It depends on your application.

  • You are calling this function only once? Don't use a function
  • Your function is really short (for instance, a one-liner)*? Don't use a function
  • You are running out of flash memory? Use a function
  • You need a lot of speed? Don't use a function (you add overhead)
  • You are not in one of the previous cases? Do as you prefer

    • With one-liner I mean something like, for instance, byte sum(byte a, byte b) { return a + b; }; in this case the function also occupies more space, since the call function instruction is compatible with the byte sum

Please note that usually more readability is more important than performances, so maybe using functions should be encouraged. I mean, in your case I'd probably use them unless there is a problem

What to do if you don't want to use a function? Well, there are other techniques:

  • Mark the function as inline; this is a hint for the compiler not to create a function but to replicate this every time. This is only a hint, so the compiler may ignore this
  • Instead of a function write a macro. This will be substituted every time, but the code will be maintainable. As a drawback, it is much harder to debug with the usual methods.

Just a remark: usually smart compilers can guess what is the best option (inline or function) on their own also for non-inline functions. So you can also trust the compiler in 90% of the cases


The reason I would tend towards the second method more is there is less opportunity for bugs in the second version.

If storage size is a major concern and you know that repeating the code requires less storage, then I would #define it as a macro and get the best of both worlds.

You could improve the code though. At the moment you are passing copies of the variable into functions, passing const references might use less room, void checkBack(const TS_Point& p){