Lorand
Lorand

Reputation: 311

Should I store numbers in chars to save memory?

The question is pretty simple. Should I store some numbers which will not surpass 255 in a char or uint_8t variable types to save memory?

Is it common or even worth it saving a few bytes of memory?

Upvotes: 2

Views: 1273

Answers (4)

MSalters
MSalters

Reputation: 179787

As a rule of thumb, int is the "natural size" of integers on your platform. You many need a few extra bytes of code to read and write variables with other sizes. Still, if you got thousands of small values, a few extra bytes of code is worth the savings in data.

So, std::vector<unsigned char> vc; makes a lot more sense than just a single unsigned char c; value.

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60058

If it's a local variable, it mostly doesn't matter (from my experience different compilers with different optimization options do (usually negligibly) better with different type choices).

If it's saved elsewhere (static memory / heap) because you have many of those entities, then uint_least8_t is probably the best choice (the least and fast types are generally guaranteed to exists; the exact-width types generally are not).

unsigned char will reliably provide enough bits too (UCHAR_MAX is guaranteed to be at least 255 and since sizeof(unsigned char) is guaranteed to be 1 and sizeof(AnyType) >= 1, there can be no unsigned integer type that's smaller).

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126203

It depends mostly on how many numbers you have to store. If you have billions of them, then yes, it makes sense to store them as compactly as possible. If you only have a few thousand, then no, it probably does not make sense. If you have millions, it is debatable.

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57678

Depends on your processor and the amount of memory your platform has. For 16-bit, 32-bit and 64-bit processors, it doesn't make a lot of sense. On a 32-bit processor, it likes 32-bit quantities, so you are making it work a little harder. These processors are more efficient with 32-bit numbers (including registers).

Remember that you are trading memory space for processing time. Packing values and unpacking will cost more execution time than not packing.

Some embedded systems are space constrained, so restricting on size makes sense.

In present computing, reliability (a.k.a. robustness) and quality are high on the priority list. Memory efficiency and program efficiency have gone lower on the priority ladder. Development costs are also probably higher than worrying about memory savings.

Upvotes: 5

Related Questions