C++ · Module 17 · Lesson 92 min read

Undefined Behaviour & Performance Tips

Undefined behaviour (UB)

Code the standard gives no meaning to. The compiler assumes UB never happens and optimizes on that basis, so results can be bizarre: wrong answers, crashes, or "working" until a new compiler version.

Common UB

UBExample
Signed integer overflowINT_MAX + 1
Out-of-bounds accessv[v.size()]
Null / dangling pointer useuse-after-free, returning a reference to a local
Uninitialized readsint x; std::cout << x;
Data racestwo threads writing without sync
Modifying a variable twice unsequencedi = i++ + 1; (now defined in C++17 for some cases, but avoid)
Invalid casts / strict aliasingreading a float through an int*
Shifting by ≥ width1 << 32 on 32-bit int
Missing return in non-void function
Defend with -Wall -Wextra, sanitizers, .at(), std::span, smart pointers.

Performance: measure first ✅

  1. Compile with optimizations: -O2 (and -DNDEBUG)
  2. Profile (perf, VTune, Visual Studio profiler, std::chrono timers) — find the actual hot spot
  3. Improve the algorithm first (O(n²) → O(n log n) beats micro-tuning)

Habits that make C++ fast

  • Pass big objects by const&; return by value (moves/elision)
  • reserve() vectors when the size is known
  • Prefer std::vector (contiguous, cache-friendly) and loop row-by-row
  • Avoid needless copies in loops: for (const auto& x : v)
  • emplace_back, std::move where ownership transfers
  • std::string_view / std::span for read-only parameters
  • constexpr to compute at compile time
  • Avoid std::endl in loops (flushes); use '\n'
  • Avoid allocation in hot loops; reuse buffers
  • unordered_map for large lookup tables; sorted vector for small/static ones

Don't sacrifice correctness

"Premature optimization is the root of all evil" (Knuth) — clear code first, then optimize measured bottlenecks.

Example

C++
#include <chrono>
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>

template <typename F>
long long time_ms(F f) {
    auto start = std::chrono::steady_clock::now();
    f();
    return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
}

bool has_duplicate_slow(const std::vector<int>& v) {          // O(n²)
    for (std::size_t i = 0; i < v.size(); ++i)
        for (std::size_t j = i + 1; j < v.size(); ++j)
            if (v[i] == v[j]) return true;
    return false;
}

bool has_duplicate_fast(const std::vector<int>& v) {          // O(n) average
    std::unordered_set<int> seen;
    seen.reserve(v.size());
    for (int x : v)
        if (!seen.insert(x).second) return true;
    return false;
}

int main() {
    std::vector<int> ids(20'000);
    for (int i = 0; i < 20'000; ++i) ids[i] = i * 3;          // no duplicates: worst case

    bool a = false, b = false;
    long long slow = time_ms([&] { a = has_duplicate_slow(ids); });
    long long fast = time_ms([&] { b = has_duplicate_fast(ids); });
    std::cout << std::boolalpha << "same answer? " << (a == b) << ", hash version faster? " << (fast <= slow) << '\n';

    std::vector<std::string> words(100'000, "budgetbuddy");
    std::size_t total = 0;
    long long copies = time_ms([&] { for (auto w : words) total += w.size(); });          // copies each string
    long long refs = time_ms([&] { for (const auto& w : words) total += w.size(); });     // no copies
    std::cout << "characters counted twice: " << total << ", const& loop not slower? " << (refs <= copies + 1) << '\n';

    std::vector<int> reserved;
    reserved.reserve(1'000'000);
    for (int i = 0; i < 1'000'000; ++i) reserved.push_back(i);
    std::cout << "reserved vector capacity unchanged: " << (reserved.capacity() == 1'000'000) << '\n';

    // UB examples are NOT run — each is a bug the sanitizers in this course would report:
    // int big = 2'147'483'647; big + 1;        signed overflow
    // std::vector<int> v(3); v[3] = 1;         out of bounds
    // int x; std::cout << x;                   uninitialized read
    long long safe = 2'147'483'647LL + 1;
    std::cout << "safe 64-bit sum: " << safe << '\n';
    return 0;
}

/* Output:
same answer? true, hash version faster? true
characters counted twice: 2200000, const& loop not slower? true
reserved vector capacity unchanged: true
safe 64-bit sum: 2147483648
*/