Cambo Freelance
ទំព័រដើមសេវាកម្មអត្ថបទការបង្រៀនក្រុមវគ្គបណ្តុះបណ្តាលទំនាក់ទំនង
Cambo Freelance

Professional freelance team from Cambodia delivering technology-driven solutions with cultural insight and modern expertise.

ផ្ញើសាររបស់អ្នក

ត្រៀមចាប់ផ្តើមគម្រោងរបស់អ្នក? ទំនាក់ទំនងក្រុមរបស់យើង។

ទំនាក់ទំនង

សេវាកម្ម

  • Web & Mobile Development Services
  • Graphic Design & Branding Services

តំណភ្ជាប់មានប្រយោជន៍

  • ទំព័រដើម
  • សេវាកម្ម
  • ការសិក្សា
  • អំពីយើង
  • ទំនាក់ទំនង
  • តម្លៃ

© 2026 Cambo Freelance. រក្សាសិទ្ធិទាំងអស់។

TelegramFacebookLinkedInEmail
HomeTutorialsC++C++ Performance Optimization
⚡C++ Tutorials

50 lessons

Beginner(21)1C++ Introduction2C++ Getting Started3C++ Syntax4C++ Output5C++ Comments6C++ Variables7C++ Data Types8C++ Constants9C++ User Input10C++ Operators11C++ Strings12C++ Math13C++ Booleans14C++ Conditions15C++ Switch16C++ Loops17C++ Break and Continue18C++ Arrays19C++ Functions20C++ References21C++ Pointers
Intermediate(19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers
Advanced(10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44
⚡

C++ Tutorials

Lesson 50 of 50

All lessons
Beginner (21)1C++ Introduction2C++ Getting Started
26
C++ Encapsulation
27C++ Inheritance
28C++ Polymorphism
29C++ Abstraction
30C++ Files
31C++ Exception Handling
32C++ Namespaces
33C++ Structures
34C++ Enumerations
35C++ STL Introduction
36C++ Vectors
37C++ Maps
38C++ Sets
39C++ Queues
40C++ Stacks
C++ Move Semantics
45C++ Multithreading
46C++ Design Patterns
47C++ Memory Management
48C++17 Features
49C++20 Features
50C++ Performance Optimization
3
C++ Syntax
4C++ Output
5C++ Comments
6C++ Variables
7C++ Data Types
8C++ Constants
9C++ User Input
10C++ Operators
11C++ Strings
12C++ Math
13C++ Booleans
14C++ Conditions
15C++ Switch
16C++ Loops
17C++ Break and Continue
18C++ Arrays
19C++ Functions
20C++ References
21C++ Pointers
Intermediate (19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers26C++ Encapsulation27C++ Inheritance28C++ Polymorphism29C++ Abstraction30C++ Files31C++ Exception Handling32C++ Namespaces33C++ Structures34C++ Enumerations35C++ STL Introduction36C++ Vectors37C++ Maps38C++ Sets39C++ Queues40C++ Stacks
Advanced (10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44C++ Move Semantics45C++ Multithreading46C++ Design Patterns47C++ Memory Management48C++17 Features49C++20 Features50C++ Performance Optimization
⚡C++AdvancedLesson 50 of 50CamboFreelanceJune 19, 2026

C++ Performance Optimization

Complete your C++ journey with performance optimization: profiling, cache-friendly code, avoiding copies, vector reserve, and compiler flags.


Tutorials › C++ › Performance Optimization
Advanced12 min readLesson 50 of 50

Why Optimize?

C++ is chosen for performance-critical applications. Understanding where time is spent — and how to reduce it — is the final skill in mastering C++.

Step 1 — Profile Before Optimizing

// Measure execution time using chrono
#include <chrono>
using namespace std::chrono;

auto start = high_resolution_clock::now();
// ... code to measure ...
auto end   = high_resolution_clock::now();
auto ms    = duration_cast<milliseconds>(end - start).count();
cout << "Elapsed: " << ms << "ms" << endl;

Use profiling tools: gprof, perf (Linux), Instruments (macOS), VTune (Intel).

Cache-Friendly Code

Modern CPUs are much faster than RAM. Access memory sequentially (row-major) to leverage the cache:

const int N = 1000;
int matrix[N][N];

// Slow — column-major, many cache misses
for (int j = 0; j < N; j++)
    for (int i = 0; i < N; i++)
        matrix[i][j] = 0;

// Fast — row-major, cache-friendly
for (int i = 0; i < N; i++)
    for (int j = 0; j < N; j++)
        matrix[i][j] = 0;

Avoid Unnecessary Copies

// Bad — copies string
void process(string s) { ... }

// Good — no copy
void process(const string& s) { ... }

// Best for rvalues — steal the string
void process(string&& s) { data = move(s); }

Reserve Vector Capacity

vector<int> v;
v.reserve(1000000);   // pre-allocate — avoids repeated reallocations

for (int i = 0; i < 1000000; i++) v.push_back(i);

Compiler Optimizations

FlagLevel
-O0No optimization (debug)
-O1Basic optimizations
-O2Moderate (recommended release)
-O3Aggressive (may increase binary size)
-OfastO3 + allow floating-point shortcuts

Key Optimization Tips

  • Prefer emplace_back over push_back to construct in-place.
  • Use unordered_map instead of map for O(1) avg lookups.
  • Avoid dynamic allocation in hot loops — allocate once, reuse.
  • Use const& for read-only parameters of non-trivial types.
  • Enable Link Time Optimization: -flto.
  • Mark hot functions inline or __attribute__((hot)).

Final Exercise

Benchmark two approaches to summing 10 million integers: (1) using a plain C array; (2) using a vector with reserve(). Measure and compare the time using chrono.

Show Solution
#include <iostream>
#include <vector>
#include <chrono>
#include <numeric>
using namespace std;
using namespace chrono;

int main() {
    const int N = 10000000;

    // Array approach
    auto t1 = high_resolution_clock::now();
    long long sum1 = 0;
    int* arr = new int[N];
    for (int i = 0; i < N; i++) arr[i] = i;
    for (int i = 0; i < N; i++) sum1 += arr[i];
    delete[] arr;
    auto t2 = high_resolution_clock::now();
    cout << "Array sum: "  << sum1 << " in " << duration_cast<milliseconds>(t2-t1).count() << "ms\n";

    // Vector approach
    auto t3 = high_resolution_clock::now();
    vector<int> v; v.reserve(N);
    for (int i = 0; i < N; i++) v.push_back(i);
    long long sum2 = accumulate(v.begin(), v.end(), 0LL);
    auto t4 = high_resolution_clock::now();
    cout << "Vector sum: " << sum2 << " in " << duration_cast<milliseconds>(t4-t3).count() << "ms\n";
    return 0;
}

Quiz

  1. Why is row-major iteration faster than column-major for 2D arrays?

    • A) Row-major uses less memory
    • B> Column-major triggers more cache misses because memory is accessed non-sequentially
    • C) Row-major uses fewer loops
    • D> The compiler automatically converts column-major
    Answer

    B) C++ stores 2D arrays in row-major order. Column-major access skips over cache lines, causing frequent cache misses and slowdowns.

Summary & Congratulations!

You have completed the full C++ Tutorial Series — from Hello World to performance optimization!

  • Profile first — optimize the bottleneck, not random code.
  • Write cache-friendly, sequential memory access patterns.
  • Avoid copies: use const&, &&, and std::move().
  • Pre-allocate with reserve() on vectors.
  • Use compiler optimization flags in release builds (-O2 or -O3).
← Previous: C++20 Features Back to C++ Tutorials Home
c++performanceoptimizationadvanced
PreviousLesson 49: C++20 Features
Series Complete!You finished all C++ lessons.
Back to All Tutorials