# Cost Model

Redline assigns a nanosecond cost estimate to each operation. These are conservative estimates based on modern x86-64 hardware. The model is intentionally pessimistic: better to reject a fast function than accept a slow one.

## Operation Costs

| Operation | Cost (ns) | Notes |
|-----------|-----------|-------|
| ALU (add, sub, mul, div) | 1 | Single arithmetic/logic op |
| Branch (if/else, match) | 1 | Branch prediction assumed |
| Array index | 1 | Direct memory access |
| Function call | 5 | Non-inlined call overhead |
| HashMap lookup | 25 | Hash + comparison |
| Heap allocation | 50 | malloc + bookkeeping |
| HashMap insert | 50 | Hash + allocate + insert |
| Mutex lock | 100 | Uncontended lock |
| String format | 200 | Formatting + allocation |
| File syscall | 1,000 | Kernel transition + I/O |
| println! | 5,000 | Format + stdout lock + flush |
| Network syscall | 10,000 | DNS/connect overhead |

## How Costs Accumulate

**Sequential:** costs add up.
```rust
let a = x + 1;    // 1ns
let b = a * 2;    // 1ns
// total: 2ns
```

**Loops:** body cost * iteration count.
```rust
for i in 0..100 {    // 100 iterations
    sum += i;         // 1ns per iteration
}
// total: 100ns + 1ns (branch) = 101ns
```

**Branches:** worst-case arm.
```rust
if condition {
    fast_path()    // 5ns
} else {
    slow_path()    // 50ns
}
// cost: 1ns (branch) + 50ns (worst case) = 51ns
```

**Nested loops:** multiply.
```rust
for i in 0..10 {
    for j in 0..10 {
        result += i * j;  // 1ns
    }
    // inner: 10ns + 1ns
}
// total: 10 * 11ns + 1ns = 111ns
```

## Why Pessimistic?

The model overestimates intentionally. If Redline says a function is under 1ms, it is almost certainly under 1ms on real hardware. The alternative (optimistic estimates) would be dangerous: accepting functions that are actually too slow.

A function rejected by Redline might be fast enough in practice. That is acceptable. A function accepted by Redline that is too slow in production is not.
