Hello! I have created a class that contains a char (8 bits, just like a Boolean), that introduces methods that can use every single bit. Now, I ran this code with an initialization of 1 million elements of a Boolean, AND this class. To my surprise, this class (1 million objects) used about 1000K of memory, whilst 1 million bools merely used 8K!
So my question is, was this a wasted effort in creating more compact Booleans?
class bitBool
{
char bits;
public:
bitBool();
bitBool(char);
~bitBool();
void setBit(int element, bool boolean);
bool getBit(int element);
};
bitBool::bitBool()
{
bits = (char) 0;
}
bitBool::bitBool(char init)
{
bits = init;
}
bitBool::~bitBool()
{}
void bitBool::setBit(int element, bool boolean)
{
char bit = ((char)std::pow(2., (double)element));
if (boolean)
bits = bits | bit; //Anything can be set if it's origin is either true of false
else
bits = bits & ~bit; //We must invert the bitset and use the AND operator.
/*
2. element false:
0010 1101 bits //Original bits
1111 1011 AND ~bit (bit == 0000 0100)
_________
0010 1011
The information is preserved this way.
*/
}
bool bitBool::getBit(int element)
{
if (bits & ((char)std::pow(2., (double)element)))
returntrue;
returnfalse;
}
#includes:
1 2 3
#include <cstdio> //std::getchar() (Just to pause an element, it's better than using std::cin >> to pause because you don't need to declare a variable)
#include <cmath> //Use for std::pow(,)
#include <iostream> //std::cin && std::cout
You wrote that "To my surprise, this class (1 million objects) used about 1000K of memory, whilst 1 million bools merely used 8K!"
Why did you conclude so? Your structure occupies 1 byte. So if the bool type also occupies one byte then the memory allocated for arrays will be equal.
I know, it should only occupy one byte (and perhaps a few more for the methods, but that's not per object), but looking at it in "Windows Task Manager" I see that allocating 1M bools increases executable size by 8K, whilst allocating 1M objects increases the executable size by almost 1000K!
From there I derive my question:
"Was this a wasted effort?", in addition, is there any solution, or what did I do wrong?
You can just use a bit shift which is the same as power of two.
int bit = 1 << element;
Also you shouldn't use windows task manager to monitor memory.
You could use templates to specify a size but the minimum will always be 1 byte, so if you have 1 million of these classes there's your problem. The template parameter will be used to create an array based on the number of bits. There is already a class that does this though in the standard library, bitset.
For your information, the class std::bitset or std::vector<bool> is exactly what you need, they are optimized for space and use only 1 byte for 8 bools.