To write software with predictable memory access patterns and maximize performance, you should avoid features that introduce indirect jumps, heap fragmentation, hidden overhead, or unpredictable control flow. Below is a breakdown of what to avoid, why, and the compiler flags to enforce these restrictions:
1. Features to Avoid and Why
a. Virtual Functions
- Why: Virtual functions use vtables, which introduce indirect jumps and cache misses.
- Avoid: Use non-virtual methods,
final classes, or composition over inheritance.
- Flag: None directly, but use
-Wnon-virtual-dtor to catch issues.
b. Exceptions
- Why: Exceptions add hidden overhead (e.g., stack unwinding, exception tables) and can disrupt control flow.
- Avoid: Use error codes or
Maybe/Result types instead.
- Flag:
-fno-exceptions
c. RTTI (Run-Time Type Information)
- Why:
dynamic_cast, typeid, and type_info add runtime overhead and memory.
- Avoid: Use
static_cast or compile-time type checks (e.g., std::is_same).
- Flag:
-fno-rtti
d. Smart Pointers
- Why:
std::unique_ptr, std::shared_ptr, and std::weak_ptr add reference counting overhead and indirection.
- Avoid: Use raw pointers with manual memory management or fixed-size buffers.
- Alternative: Use
std::array or std::span for fixed-size data.
e. Dynamic Memory Allocation
- Why:
new/delete and malloc/free can lead to heap fragmentation and unpredictable access patterns.
- Avoid: Use stack allocation, pre-allocated buffers, or
alloca (carefully).
- Alternative: Use
std::vector with reserve() to preallocate memory.
f. STL Containers with Unpredictable Access
- Why:
std::map, std::set, std::unordered_map (hash tables) have indirect memory access.
- Avoid: Use contiguous arrays (
std::array, std::vector) or flat data structures (e.g., sorted arrays with binary search).
- Alternative: Use
std::unordered_map only if cache locality is acceptable.
g. Lambdas and Closures
- Why: Lambdas generate hidden objects and can introduce indirect jumps.
- Avoid: Use function pointers or inline functions instead.
h. Variadic Templates and Template Metaprogramming
- Why: Overuse can lead to code bloat and compile-time overhead.
- Avoid: Minimize template usage unless necessary.
i. Move Semantics
- Why:
std::move and rvalue references can introduce hidden copies or branch mispredictions.
- Avoid: Use value semantics or raw pointers for transfers.
j. Thread-Local Storage (TLS)
- Why: TLS has indirect access and synchronization overhead.
- Avoid: Use global/static variables or explicit thread-local data structures.
2. Compiler Flags to Enforce These Restrictions
a. Disable Unwanted Features
# Disable exceptions, RTTI, and thread-local storage
-fno-exceptions -fno-rtti -fno-threadsafe-statics -fno-thread-local-storage
# Disable C++11+ features (if needed)
-std=c++03 # Enforce older C++ standards to avoid modern features
b. Optimize for Speed and Predictability
# Optimize for speed (not size)
-O3
# Enable link-time optimization to reduce redundancy
-flto
# Aggressive inlining (use sparingly; may increase binary size)
-finline-functions -finline-limit=10000
# Disable stack protection (security vs. performance trade-off)
-fno-stack-protector
c. Enable Warnings and Strict Checks
# Enable warnings for indirect jumps and undefined behavior
-Wpointer-arith -Wcast-align -Wuninitialized -Wstrict-aliasing
# Warn about exceptions (if accidentally used)
-Wunused-but-set-parameter -Werror
# Enforce noexcept on functions with no exceptions
-Wnoexcept
d. Reduce Code Bloat
# Remove unused code and sections
-fdata-sections -ffunction-sections
-Wl,--gc-sections
# Strip debug symbols in release builds
-s
3. Coding Practices for Predictable Memory Access
a. Use Contiguous Data Structures
b. Preallocate Memory
c. Avoid Dynamic Polymorphism
d. Use Stack Allocation
e. Minimize Indirection
f. Optimize Cache Locality
- Arrange data in memory to match access patterns (e.g., arrays of structs vs. structs of arrays).
- Example:
// Bad (cache-unfriendly):
struct {
float x, y, z;
} points[1000];
// Better (cache-friendly):
float x[1000], y[1000], z[1000];
4. Example Command-Line
g++ -std=c++03 \
-O3 -flto -fno-exceptions -fno-rtti \
-fno-threadsafe-statics -fno-stack-protector \
-Wall -Wextra -Werror \
-Wnoexcept -Wpointer-arith -Wcast-align \
-fdata-sections -ffunction-sections \
-Wl,--gc-sections \
-o my_program source.cpp
Key Takeaways
- Avoid dynamic polymorphism (virtual functions, exceptions, RTTI).
- Use contiguous memory and preallocated buffers.
- Minimize indirection (raw pointers, avoid smart pointers).
- Optimize for cache locality (contiguous data, aligned structures).
- Compiler flags enforce strictness and reduce overhead.
By combining these practices, you’ll achieve predictable memory access patterns and maximize performance in your software.