Let's consider a simple c struct:
struct foo { const char * str; unsigned char flag; uint64_t len; };
Suppose that this code is being run as a part of a program executing on a 64-bit machine: what would you expect the result of sizeof(struct foo) to be?
Most people that never had to mess with struct sizes and optimizations would guess that it should be 17...
... but it's 24! Why is that?
The reason for this behavior is that compilers optimize struct layouts for speed, and it's the modern norm that aligned memory accesses are the fastest way to access data.
This means that, depending on the type of field and cpu, your data will have some alignment and will be positioned such that that alignment is respected (or, such that field-address % field-alignment == 0).
size, alignment, padding
In the case of the previous example, pointers and 64-bit fields are 8B aligned on 64-bit machines, and this means that, in order to force a layout where everything in the struct is aligned, the compiler will generate some padding between the flag and len fields:
Now let's consider another example, where a struct like this is defined, on the same machine as before:
struct bar { const char * str; short s1; int i1 short s2; int i2; };
How do we go about computing its size?
There are three rules:
- Struct fields want to be aligned with their own natural alignment.
- The overall struct alignment is equal to the alignment of its widest field
- If you had to put two structs of the same type side by side, the second one should be aligned to its alignment -- this means that structs must have trailing padding up to their alignment
Quick recap on basic types alignment and size for 64-bit machines:
type | size | alignment |
---|---|---|
char | 1 | 1 |
short | 2 | 2 |
int | 4 | 4 |
long | 8 | 8 |
float | 4 | 4 |
double | 8 | 8 |
pointers | 8 | 8 |
Also remember that:
- Arrays have the alignment of their value type, and size that is sizeof(type) * elements number.
- Unions have the alignment and size of their widest member.
And you can use the super useful sizeof and _Alignof operators to get this information for your custom types. Note that _Alignof is available from C11 onward, and is called alignof starting with C23. It was always alignof from what I understand in C , since C 11.
For more information, the bible on this topic is The Lost Art of Structure Packing, from which I learned almost everything I know about this, together with a lot of practice and hands-on experience.
optimizing your structs: stropt
This topic here is something that comes up rather frequently at work, where saving bytes here and there is super important when sending huge loads of data continuously in queues and whatnot.
In order to make my life easier, I wrote a tool that produces some statistics on a type you pass as input, with reference to a source file or code snippet, it's called stropt (struct optimizer).
Abathargh/stropt on GitHub
build & install
If you have a local go installation you can go right ahead and build or install the application directly:
struct foo { const char * str; unsigned char flag; uint64_t len; };
Already compiled binaries for a list of os/archs combinations are also provided in the github release page:
stropt binaries
using the tool
You can either use stropt by passing the source to analyze as a string:
struct bar { const char * str; short s1; int i1 short s2; int i2; };
Or you can pass a file in which the definition is contained:
git clone https://github.com/Abathargh/stropt go build // or, if you want to install this directly go install github.com/Abathargh/stropt
The tool can also provide a possible optimization for your types by using the -optimize flag, and it's aware of fields that are structs themselves:
Note that the verbose flag is used to show inner structs (and unions) along with their fields alignment and size.
what's next
This tool was written in go using the great modernc.org/cc C compiler front-end for parsing C code, and lipgloss from charmbracelet for the UI.
I'm writing this for myself but I'm happy to share it publicly; I'd like to make this a webapp for easier use directly in a browser, so probably that's the next thing I'm going to be working on!
The above is the detailed content of optimizing c structs layouts. For more information, please follow other related articles on the PHP Chinese website!

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
