Lam NguyenAlgorithms

Performance Optimization

Updated November 18, 2026

Topics
  1. Contest Setup
  2. Binary Search
  3. Dynamic Programming
  4. Range Queries
  5. Priority Queues
  6. Stacks
  7. Hashing
  8. Strings
  9. Graphs and Trees
  10. Graph Theory
  11. Network Flow
  12. Combinatorics
  13. Algebra
  14. Data Structure Design
  15. Performance Optimization
  16. Databases
  17. Selected LeetCode Problems

Making correct code faster. The rule on this page: measure where the time goes, change one thing at a time, and credit each speedup to the change that actually caused it. A faster submission after two changes says nothing about which one helped.

C++ template used by every implementation on this page

Each implementation below starts after this header.

#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using i64 = int64_t;
using u64 = uint64_t;
using i128 = __int128;
using u128 = unsigned __int128;

using vi = vector<int>;
using vii = vector<vector<int>>;
using pii = pair<int, int>;

#define REP(i, n) for (int i = 0; i < (n); i++)
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
#define RFOR(i, n) for (int i = (n) - 1; i >= 0; i--)

#define all(x) (x).begin(), (x).end()
#define sz(x) (int)((x).size())

#define fi first
#define se second
#define pb push_back

const int INF = 1e9+7;
const int MOD = 1e9+7;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());

Lambdas as Callbacks

In his CppCon 2017 talk When a Microsecond Is an Eternity: High Performance Trading Systems in C++, Carl Cook has a slide called “Lambda functions are fast and convenient” with one rule on it: if you know at compile time which function is to be executed, then prefer lambdas.

template <typename T>
void SendMessage(T&& lambda) {
    Msg msg = PrepareMessage();
    lambda(msg);
    send(msg);
}

SendMessage([&](auto& msg) {
    msg.instrument = x;
    msg.price = z;
});

SendMessage owns the fixed steps, preparing and sending. The caller fills in the step in the middle. The question is what that flexibility costs.

Why a lambda is free

Every lambda expression has its own unnamed type. Passed as T&&, it makes the compiler build a separate copy of SendMessage for that one type, and inside that copy lambda(msg) can only mean one function. So the compiler can inline it, and the result is the same code as writing the body there by hand.

The other two ways to pass behavior give every callable of a signature the same type:

When the target is a constant in the same file, the compiler can sometimes see through both. The template with a lambda guarantees it.

Inlining saves more than the call. Once the body is inline, the compiler optimizes it together with the loop around it. Summing \(f(x) = 3x + 1\) over \(2^{20}\) ints, with the pointer and the std::function chosen at runtime so the compiler can’t see their target:

Callback ns per element
template + lambda 0.074
std::function 0.890
function pointer 0.866

That is a factor of about \(12\), and most of it is not the call. The lambda loop is vectorized: it uses SIMD instructions (movi.4s), four ints per register. The other two loops make an indirect call (blr) for every element, and a loop with an opaque call in it cannot be vectorized.

A smaller version: LeetCode 359

LeetCode 359 — Logger Rate Limiter streams messages with non-decreasing timestamps, at most \(10^4\) calls. A message is printed only if the same message was not printed in the last \(10\) seconds. The same shape fits: a generic processEvent decides whether an event goes through, and the caller says what happens when it does.

// if you know at compile time which function is to be executed, then prefer lambdas
template <typename Callback>
bool processEvent(int ts, int next_ts, Callback&& onAccept) {
    if (ts < next_ts) return false;
    onAccept(ts);
    return true;
}

class Logger {
private:
    unordered_map<string, int> ntime;

public:
    Logger() {}

    bool shouldPrintMessage(int ts, string msg) {
        int& next_ts = ntime[msg];
        return processEvent(ts, next_ts, [&](int ts) {
            next_ts = ts + 10;
        });
    }
};

ntime[msg] returns a reference to the message’s slot and inserts \(0\) if the message is new. Timestamps are at least \(0\), so \(0\) already means “never printed”, with no special case. The lambda captures that reference and writes the next allowed time through it, so the map is searched once per call.

Where the time goes

Changing map to unordered_map took this from 17 ms to 15 ms on LeetCode. Two things are in play, the lambda and the map, so measure each. Below: \(10^4\) calls over \(1000\) distinct messages of length \(1\) to \(30\), median of \(15\) runs, Apple clang 15 at -O2 on an M2 Pro.

Version ns per call
map, lambda 105
unordered_map, lambda 45
unordered_map, body written inline 43
unordered_map, std::function or fn pointer 44–49
unordered_map, find then [] 52
unordered_map, const string& 33

The whole run of \(10^4\) calls takes about \(1\) ms with map and \(0.45\) ms with unordered_map here. Most of LeetCode’s 15 ms is the judge, not the logger, and the same code can come back a few ms apart on two submissions. So the 2 ms points the right way, and the measurement says which change earned it.

The takeaway

Practice

Lambdas as Callbacks

Further reading

Lambdas as Callbacks