Optimization Basics
Modern compilers are very good at generating fast code, so hand-written assembly is only worth it when you know why something is slow. This lesson collects the principles that matter most on today's x86-64 CPUs. Timing measurements are not reproducible in a shared playground, so the examples here show the techniques and use NASM itself to measure code size, one of the few performance properties that is fully deterministic.
How a modern CPU executes code
- Pipelining and superscalar execution. A core decodes and executes about 4–6 instructions per cycle if they don't depend on each other.
- Out-of-order execution. Instructions run as soon as their inputs are ready, not strictly in program order.
- Branch prediction. The CPU guesses the direction of every jump. A wrong guess costs ~15–20 cycles.
- Caches. An L1 hit takes ~4 cycles, main memory ~100+. Memory access patterns often matter more than instruction counts.
Rough latencies on a recent core: add/and/mov reg, reg 1 cycle, imul 3, L1 load 4–5, div r64 15–40+, a mispredicted branch ~15–20, a cache miss to RAM ~200+.
Measuring instruction sizes
Subtracting two labels gives the number of bytes in between, so NASM can tell us how big different encodings are. Smaller code fits better in the instruction cache and decoders:
section .text
global _start
_start:
mov edi, zero_b - zero_a
call print_uint ; mov rax, 0
mov edi, zero_c - zero_b
call print_uint ; xor eax, eax
mov edi, one_b - one_a
call print_uint ; mov rax, -1 (as a 64-bit immediate)
mov edi, one_c - one_b
call print_uint ; or rax, -1 (sign-extended 8-bit immediate)
mov edi, inc_b - inc_a
call print_uint ; add rcx, 1
mov edi, inc_c - inc_b
call print_uint ; inc ecx
mov eax, 60
xor edi, edi
syscall
; never executed: these instructions only exist to be measured
zero_a: mov rax, strict qword 0
zero_b: xor eax, eax
zero_c:
one_a: mov rax, strict qword -1
one_b: or rax, -1
one_c:
inc_a: add rcx, 1
inc_b: inc ecx
inc_c:
; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
mov rax, rdi ; rax = the number to convert
sub rsp, 32 ; room for up to 20 digits and a newline
lea rsi, [rsp + 31] ; fill the buffer from its end
mov byte [rsi], 10 ; the newline is the last character
mov ecx, 10
.next_digit:
xor edx, edx ; the dividend is rdx:rax, so clear rdx
div rcx ; rax = quotient, rdx = remainder (0..9)
add dl, '0' ; remainder -> ASCII digit
dec rsi
mov [rsi], dl ; store it in front of the previous one
test rax, rax
jnz .next_digit ; repeat until the quotient is 0
lea rdx, [rsp + 32]
sub rdx, rsi ; rdx = number of bytes to print
mov eax, 1 ; write(1, rsi, rdx)
mov edi, 1
syscall
add rsp, 32
ret10
2
10
4
4
2
strict qword forces the long encoding; without it NASM's optimizer would already pick a shorter form for mov rax, 0. Choosing short idioms — xor eax, eax, 32-bit registers, small immediates — is free performance.
Avoid slow instructions
| Instead of | Prefer | Why |
|---|---|---|
div by a constant |
multiply by the reciprocal + shift | 3–4 cycles instead of 20+ |
imul by 2, 4, 8 / 3, 5, 9 |
shl / lea |
1 cycle instead of 3 |
loop |
dec + jnz |
loop is microcoded and slow on most CPUs |
mov eax, 0 before arithmetic |
xor eax, eax |
shorter, breaks dependencies |
partial registers (mov al, … then reading eax) |
movzx to a full register |
avoids partial-register stalls/merges |
push/pop pairs in a hot loop |
keep values in registers | fewer memory operations |
Unpredictable branches
A branch that goes randomly one way or the other is mispredicted about half the time. Replacing it with arithmetic or cmov removes the penalty. Both of these count the values below 50, with identical results — but on random data the branch-free version is typically several times faster:
section .data
data: dq 73, 12, 98, 45, 3, 67, 50, 21, 88, 34, 9, 56
COUNT equ ($ - data) / 8
section .text
global _start
_start:
; version 1: a branch per element
xor edi, edi
xor ecx, ecx
.branchy:
cmp qword [data + rcx*8], 50
jae .skip
inc rdi
.skip:
inc ecx
cmp ecx, COUNT
jb .branchy
call print_uint
; version 2: the comparison's carry is the count
xor edi, edi
xor ecx, ecx
.branchless:
cmp qword [data + rcx*8], 50 ; CF = 1 if the value is below 50
adc rdi, 0 ; add the carry
inc ecx
cmp ecx, COUNT
jb .branchless
call print_uint
mov eax, 60
xor edi, edi
syscall
; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
mov rax, rdi ; rax = the number to convert
sub rsp, 32 ; room for up to 20 digits and a newline
lea rsi, [rsp + 31] ; fill the buffer from its end
mov byte [rsi], 10 ; the newline is the last character
mov ecx, 10
.next_digit:
xor edx, edx ; the dividend is rdx:rax, so clear rdx
div rcx ; rax = quotient, rdx = remainder (0..9)
add dl, '0' ; remainder -> ASCII digit
dec rsi
mov [rsi], dl ; store it in front of the previous one
test rax, rax
jnz .next_digit ; repeat until the quotient is 0
lea rdx, [rsp + 32]
sub rdx, rsi ; rdx = number of bytes to print
mov eax, 1 ; write(1, rsi, rdx)
mov edi, 1
syscall
add rsp, 32
ret6
6
Breaking dependency chains
Out-of-order cores can only overlap independent work. A single accumulator makes every add wait for the previous one; two or more accumulators let additions run in parallel. Unrolling also reduces the loop overhead per element:
section .data
values: dq 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
COUNT equ ($ - values) / 8 ; a multiple of 4
section .text
global _start
_start:
xor eax, eax ; accumulator A
xor edx, edx ; accumulator B
xor r8d, r8d ; accumulator C
xor r9d, r9d ; accumulator D
xor ecx, ecx
.loop: ; 4 independent additions per iteration
add rax, [values + rcx*8]
add rdx, [values + rcx*8 + 8]
add r8, [values + rcx*8 + 16]
add r9, [values + rcx*8 + 24]
add ecx, 4
cmp ecx, COUNT
jb .loop
add rax, rdx ; combine at the end
add r8, r9
lea rdi, [rax + r8]
call print_uint
mov eax, 60
xor edi, edi
syscall
; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
mov rax, rdi ; rax = the number to convert
sub rsp, 32 ; room for up to 20 digits and a newline
lea rsi, [rsp + 31] ; fill the buffer from its end
mov byte [rsi], 10 ; the newline is the last character
mov ecx, 10
.next_digit:
xor edx, edx ; the dividend is rdx:rax, so clear rdx
div rcx ; rax = quotient, rdx = remainder (0..9)
add dl, '0' ; remainder -> ASCII digit
dec rsi
mov [rsi], dl ; store it in front of the previous one
test rax, rax
jnz .next_digit ; repeat until the quotient is 0
lea rdx, [rsp + 32]
sub rdx, rsi ; rdx = number of bytes to print
mov eax, 1 ; write(1, rsi, rdx)
mov edi, 1
syscall
add rsp, 32
ret78
Memory matters most
- Access memory sequentially. Walking an array in order lets the hardware prefetcher stream data in; jumping around (linked lists, column-wise traversal of a row-major matrix) causes cache misses.
- Keep data small. Using
ddinstead ofdqwhen values fit halves the memory traffic. - Align hot data and loop entries (
align 16/align 64) so they don't straddle cache lines. - Keep hot values in registers instead of reloading them from memory in every iteration.
The golden rules
- Measure first. Use
perf stat,perf recordand tools such asllvm-mcaor uops.info instead of guessing. - Fix the algorithm before the instructions. An O(n log n) sort in C beats an O(n²) sort in perfect assembly.
- Read the compiler's output before rewriting a function by hand — it may already be optimal.
- Keep the slow, readable version and test the fast one against it, as the examples above do.
Test yourself
Why can a branch-free version of a loop be faster on random data?
- It uses fewer registers
- It avoids branch mispredictions, which cost ~15-20 cycles each
- Branches are illegal in loops
- cmp is slow
Why does using several accumulators speed up a summing loop?
- It uses less memory
- Independent additions can execute in parallel instead of waiting for each other
- It avoids the carry flag
- It reduces code size
What should you do before optimizing a function in assembly?
- Rewrite it immediately
- Measure where the time goes and check the compiler's output
- Remove all comments
- Inline every call