The declaration of optimizing BOOL variables in C + +

Source: Internet
Author: User
Tags bool

Normally we would declare the BOOL variable:

class CMyClass {
...
BOOL m_bVar1;
BOOL m_bVar2;
BOOL m_bVar3;
BOOL m_bVar4;
BOOL m_bVar5;
BOOL m_bVar6;
BOOL m_bVar7;
BOOL m_bVar8;
...
};

Considering that the bool variable is actually an int under the Win32, which occupies 4 bytes, the above 8 bool variables will take up 32 bytes.

typedef int BOOL; BOOL takes 4 bytes

In fact, we can change the declaration of the bool variable so that it only takes up one bit:

class CMyClass {
...
BOOL m_bVar1:1;
BOOL m_bVar2:1;
BOOL m_bVar3:1;
BOOL m_bVar4:1;
BOOL m_bVar5:1;
BOOL m_bVar6:1;
BOOL m_bVar7:1;
BOOL m_bVar8:1;
...
};

In the code above, each bool variable takes up only one bit (bit), and the top 8 bool variables take up 1 bytes.

Memory savings of 32 times times!!!

However, on the other hand, the CPU in processing these bit type bool variables, the need to do bit operations to take out the value of them, so it will consume additional CPU resources. The relationship between memory and speed needs to be taken into account when using.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.