DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.

← Back to Questions
MediumTheory

Struct Field Alignment and Memory Optimization

33 views

Problem Statement

At a high-frequency trading firm, every byte matters. A poorly aligned struct wastes 40% memory. Explain struct alignment and optimize a given struct layout.

The Problem: Padding Waste

// BAD: 24 bytes due to padding
type BadStruct struct {
    a bool    // 1 byte + 7 padding
    b int64   // 8 bytes
    c bool    // 1 byte + 7 padding
}

// GOOD: 16 bytes (reordered)
type GoodStruct struct {
    b int64   // 8 bytes
    a bool    // 1 byte
    c bool    // 1 byte + 6 padding
}

Alignment Rules

TypeSizeAlignment
bool, int8, uint81 byte1 byte
int16, uint162 bytes2 bytes
int32, uint32, float324 bytes4 bytes
int64, uint64, float64, pointer8 bytes8 bytes

Use fieldalignment Tool

go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest

fieldalignment -fix ./...

# Output:
# struct of size 24 could be 16

Practical Exercise

// Optimize this struct:
type User struct {
    IsActive   bool      // 1
    Age        int32     // 4
    ID         int64     // 8
    IsVerified bool      // 1
    Score      float64   // 8
    Flags      uint8     // 1
}

// Before: 40 bytes
// After optimization: 32 bytes
type UserOptimized struct {
    ID         int64     // 8
    Score      float64   // 8
    Age        int32     // 4
    IsActive   bool      // 1
    IsVerified bool      // 1
    Flags      uint8     // 1 + 1 padding
}

When It Matters

  • Millions of structs in memory (caches, databases)
  • CPU cache efficiency (cache line = 64 bytes)
  • Network protocols with fixed layouts

Sample Test Cases

Case 1
Input
struct { a bool; b int64; c bool }
Expected Output
Size: 24 bytes (with padding)
Case 2
Input
struct { b int64; a bool; c bool }
Expected Output
Size: 16 bytes (optimized order)

No solutions yet

Be the first to share a solution for this question.

Comments (0)

Sign in to leave a comment.

No comments yet. Be the first to comment.

Stats

Views
33
Likes
0
Solutions
0
Comments
0

Category

Backend Engineering

Languages

Go