You're on the right track by focusing on predictable memory access and avoiding runtime overhead. Here's a comprehensive guide to additional things to avoid, why, and how to disable them with compiler flags:
1. Avoid Dynamic Memory Allocation (Heap Allocations)
Why?
- Heap allocations (
new, malloc) are slow and unpredictable:
- They involve searching for free memory blocks.
- Fragment memory, leading to cache misses.
- Triggers OS calls (e.g.,
sbrk, mmap).
Alternatives:
- Stack allocations (e.g.,
int arr[1024];). Fast and cache-friendly.
- Arena allocators (preallocate a large chunk, manage manually).
- Static memory (global arrays,
constexpr).
Flags to enforce scrutiny:
-Walloca # Warn about alloca (stack allocation)
-Walloca-larger-than=N # Warn if allocation exceeds N bytes
2. Minimize Indirect Function Calls
Why?
- Virtual functions, function pointers, and
std::function cause:
- Branch prediction failures (CPU stalls).
- Indirect jumps, bypassing instruction prefetch.
What to avoid:
virtual methods (unless absolutely necessary).
std::function (type-erased callable).
- Function pointers (use
constexpr function tables instead).
Alternatives:
- Static polymorphism (CRTP: Curiously Recurring Template Pattern).
- Explicit function tables (e.g.,
switch or constexpr arrays of lambdas).
Flags:
-Wsuggest-override # Warn if virtual functions lack `override`
-Wnon-virtual-dtor # Warn about non-virtual destructors in base classes
3. Disable Runtime Type Information (RTTI)
Why?
dynamic_cast, typeid embed type metadata in binaries, bloating them.
- Adds runtime checks, slowing down execution.
Already mentioned flag:
-fno-rtti # Disable RTTI entirely
4. Avoid C++ Exceptions
Why?
- Exceptions unwind the stack, destroying objects, and invoke error handlers.
- Zero-cost exceptions (modern C++) still add metadata to binaries.
- Branch prediction suffers due to rare (but costly) error paths.
Alternatives:
- Error codes (
std::optional, std::variant, errno).
assert for debug builds (fail fast).
Flags:
-fno-exceptions # Disable exception handling machinery
-fno-unwind-tables # Strip exception unwind metadata (smaller binaries)
-fno-asynchronous-unwind-tables # Further reduce metadata
Verify:
-Wnoexcept-type # Warn about noexcept mismatches
5. Limit std::thread and Concurrency Features
Why?
- Threads introduce synchronization overhead (locks, atomics).
std::async, std::future hide thread pools, leading to unpredictable behavior.
Alternatives:
- Manual threading with
pthread (Linux) or CreateThread (Windows).
- SIMD parallelism (e.g., OpenMP,
#pragma omp simd).
Flags:
-fno-threadsafe-statics # Disable thread-safe initialization of static variables
Analysis flags (Clang):
-fsanitize=thread # Detect thread safety issues (debug builds)
6. Avoid std::map, std::unordered_map, and Other Node-Based Containers
Why?
- Node-based containers (
std::map, std::list, std::set):
- Allocate/deallocate nodes randomly → cache misses.
- Non-contiguous memory → poor spatial locality.
Alternatives:
std::vector for lists (reserve upfront).
std::array for fixed-size arrays.
- Sorted arrays + binary search (e.g.,
std::sort + std::lower_bound).
Flags:
None directly, but enable:
-Wpadded # Warn about struct padding (optimize struct layout)
7. Watch Out for Implicit Copies/Moves
Why?
- Unintentional copies of large objects (
std::string, std::vector) waste cycles.
- Move semantics can still trigger complex destructors.
Alternatives:
- Pass by
const& instead of by value.
std::span or std::string_view for non-owning views.
Flags:
-Wclass-memaccess # Warn about memcpy/memset on non-trivial types
-Wsuggest-move # Identify missed move opportunities
8. Disable iostreams and std::string (if possible)
Why?
std::cout, std::fstream are type-safe but slow:
- Heavy use of locales, facets, and virtual functions.
std::string does small-string optimization (branchy) and heap allocations.
Alternatives:
printf, fwrite (C-style I/O).
- Stack-allocated buffers (
char buf[256]; snprintf(buf, ...)).
Flags:
None directly, but compile with:
-Wformat # Check printf/scanf correctness
-Wformat-overflow=N # Warn about buffer overflows in printf
9. Flatten Deep Templates (Avoid Template Metaprogramming Bloat)
Why?
- Heavy TMP (template metaprogramming) explodes compilation time and binary size.
- Recursive templates cause long compile chains.
Alternatives:
constexpr functions (C++11+) instead of SFINAE.
- Macros (ugly but fast compile-time evaluation).
Flags:
-fconstexpr-depth=N # Limit constexpr recursion (default: 512)
-fconstexpr-steps=N # Limit constexpr evaluation steps (default: 1M)
-ftemplate-backtrace-limit=N # Limit template instantiation stack traces
10. Avoid std::function and Type-Erased Containers
Why?
std::function stores arbitrary callables (heap alloc, virtual call).
std::any, std::variant add runtime checks.
Alternatives:
- Function pointers or
constexpr jump tables.
- Tagged unions (manual
variant-like structs).
Flags:
-Wnon-virtual-dtor # Catch issues with type-erased destructors
Summary of Key Flags
Here's a "no-nonsense" compiler command:
g++ -std=c++11 \
-Wall -Wextra -Werror \
-fno-exceptions -fno-rtti -fno-threadsafe-statics \
-Os -flto -ffast-math \
-fdata-sections -ffunction-sections -Wl,--gc-sections \
-Wnoexcept -Wsuggest-override -Wold-style-cast \
-Wpadded -Wclass-memaccess \
source.cpp -o fast_program
For Clang (extra strictness):
clang++ -std=c++11 \
-Weverything -Wno-c++98-compat -Wno-padded \
-fno-exceptions -fno-rtti \
-Os -flto -ffast-math \
-fsanitize=address -fsanitize=undefined \
source.cpp -o fast_program
Runtime Profiling Tools
Even with these flags, measure performance:
perf (Linux): Analyze cache misses, branch mispredictions.
perf stat -d ./fast_program
gprof: Profile function hotspots.
g++ -pg source.cpp -o profiled_program
./profiled_program
gprof ./profiled_program > profile.txt
godbolt.org: Inspect generated assembly. Ensure no surprises (e.g., hidden new, typeid).
By following these guidelines, you'll write cache-friendly, branch-predictable, allocation-minimal C++ code. Happy optimizing! 🚀