Memory Usage

Question, trying to save memory. I had a program that had all the variables and functions in one ino file. I have since then move several to classes that are used in specific functions in the ino file. So, when a class is used in a function vs have it in the main ino file does the class get loaded when the function get called and then release when the function end. I moved them to classes to make it easier to maintain.


Your code?

Please use code tags.

Read this before posting a programming question

How to use this forum

So, when a class is used in a function vs have it in the main ino file does the class get loaded ...

You are mixing things up there. It can be in a function in the main ino file.

There are four basic kinds of variable:

  1. Instantiated global or static
  2. Uninstantiated global or static (aka BSS)
  3. Dynamically allocated
  4. Function local variables

When you create one of the first two kinds of variables it is placed at the bottom of the memory space - instantiated first, uninstantiated ones second. Above that goes the heap, which contains any dynamically allocated variables (memory allocated by malloc() or new()). Then there is the “free” space. Finally, at the top of memory, is the stack. In the stack goes (amongst other things) the function local variables.

Global / static variables are created at compile time and can be reported by the IDE as an amount of RAM used. The other kinds are created on the fly by the program - the IDE has no clue what they are or how big they are, or how many of them. When you enter a function the variables in use in that function are allocated on the stack. When you leave the function that stack space is released to be reused by the next function call - whatever function that is.

So yes, creating a class, or any form of variable (a class is just a very very fancy variable) inside a function instead of creating it globally, will appear to use less memory. In fact it will use just the same amount of memory, but unlike a global it won’t be using it all the time - it can share it with other variables in other functions depending on what functions call which other functions and in what order etc.