Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

Why is a boolean 4 bytes in .NET?

Why does a System.Boolean take 4 bytes? It just stores one state, either true or false, which could be stored in less space than 4 bytes.

question from:https://stackoverflow.com/questions/294905/why-is-a-boolean-4-bytes-in-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A bool is actually only 1 byte, but alignment may cause 4 bytes to be used on a 32-bit platform, or even 8 bytes on a 64-bit platform. For example, the Nullable<bool> (aka bool?) type uses a full 32 or 64 bits—depending on platform—even though it's comprised of just two bools. EDIT: As pointed out by Jon Skeet, padding for alignment isn't always present. As an example, an array of Nullable<bool>s takes only 2 bytes per object instead of 4 or 8.

But even 8 bits to represent a bool can be considered wasteful if you have many of them to store. For this reason, if you create a type that has many bools as members, (or uses many Nullable<> types), and users of your class might create many instances of it, you might consider using a BitVector32 instead. The framework itself uses this technique to reduce the memory footprint of many of the Windows Forms controls, for instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...