Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing for space instead of speed in C++

When you say "optimization", people tend to think "speed". But what about embedded systems where speed isn't all that critical, but memory is a major constraint? What are some guidelines, techniques, and tricks that can be used for shaving off those extra kilobytes in ROM and RAM? How does one "profile" code to see where the memory bloat is?

P.S. One could argue that "prematurely" optimizing for space in embedded systems isn't all that evil, because you leave yourself more room for data storage and feature creep. It also allows you to cut hardware production costs because your code can run on smaller ROM/RAM.

P.P.S. References to articles and books are welcome too!

P.P.P.S. These questions are closely related: 404615, 1561629

like image 609
Emile Cormier Avatar asked Jan 17 '10 21:01

Emile Cormier


People also ask

Which is better approach for allocating storage size if we need better performance speed?

Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread. Memory allocation and de-allocation is faster as compared to Heap-memory allocation. Stack-memory has less storage space as compared to Heap-memory.

What is the Optimisation of space?

Space optimization is about making the most effective use of real estate. If you're leasing an office that's too big and paying for unused space, that's not good space optimization. But, if your workplace is carefully configured to include in-demand types of workspaces and accommodate everyone, it's well-optimized.


1 Answers

My experience from an extremely constrained embedded memory environment:

  • Use fixed size buffers. Don't use pointers or dynamic allocation because they have too much overhead.
  • Use the smallest int data type that works.
  • Don't ever use recursion. Always use looping.
  • Don't pass lots of function parameters. Use globals instead. :)
like image 129
Tim Lovell-Smith Avatar answered Oct 14 '22 00:10

Tim Lovell-Smith