Golang Structs Caveats
By default Go initiates empty structs (as well as other variable types) with empty fields.
The question is next - let's assume we have next struct:
Total 1 byte for bool, 2 bytes for int16 and 2 for float32 = 7 bytes.? Not so, because we have int16 after bool, Go will use padding - use memory in same amount as next declared field requires. That means if we have field that requires 2 bytes after field that requires 1 byte, Go will require 1 more byte as a padding for "1 byte" field. If we use fields like int64 - 8 bytes, on every object we will spend extra 7 bytes.
What is the solution? Declare "heavy" fields first, than "light" ones.
The question is next - let's assume we have next struct:
type Example struct {
ready bool,
num int16,
q float32,
}
Total 1 byte for bool, 2 bytes for int16 and 2 for float32 = 7 bytes.? Not so, because we have int16 after bool, Go will use padding - use memory in same amount as next declared field requires. That means if we have field that requires 2 bytes after field that requires 1 byte, Go will require 1 more byte as a padding for "1 byte" field. If we use fields like int64 - 8 bytes, on every object we will spend extra 7 bytes.
What is the solution? Declare "heavy" fields first, than "light" ones.
type Example struct {
num int16,
q float32,
ready bool,
}
Comments
Post a Comment