Static vs. non-static - Execution time and memory use

I have an update function that I call every 4ms. In that function I declare two arrays, they do not need to persist once the update function has returned.

uint16_t data1[129], data2[129];

Would it be better to declare these as static to remove the time taken to allocate and de-allocate the memory?

When to use the Heap?

When should you use the heap, and when should you use the stack? If you need to allocate a large block of memory (e.g. a large array, or a big struct), and you need to keep that variable around a long time (like a global), then you should allocate it on the heap. If you are dealing with relatively small variables that only need to persist as long as the function using them is alive, then you should use the stack, it’s easier and faster. …

1 Like

Thanks @BulldogLowell, that link explains a lot although what is considered as a large block of memory? and does that mean static variables are stored on the heap?

I think I should just allocate them on the stack as non-static variables as I don’t need them outside the function and it’s faster than the heap, unless they are considered too large?

Without knowing how much stack is available, you run the risk of overflow. I would recommend that you make them static. Also, you can declare them static inside of the function that access them. They will still be static, but they will only be accessible inside the function scope. Best of both worlds.

void myFunction(void)
   static   uint16_t data1[129], data2[129];

   // Use my local, static arrays without fear of trashing my stack nor of anyone else getting their mitts on them.


There is no memory allocation - it’s simply moving the stack pointer, so the “allocation” is just a single machine instruction.

Making them static will avoid the possibility of stack corruption, but <300 bytes is not a problem. The stack is 2k.

For the record, it’s actually 516 bytes. And while that is still well below the 2k available, without knowing what else is happening on his photon it may actually be a problem. I still recommend making them static.

1 Like

That’s true - I quickly glanced at the array sizes and not the data type.

I agree - static is better generally.

1 Like

OK, static it is. Thanks guys :slight_smile: