name: efficient-code description: Write performant code by default — avoid O(n²), redundant work, unnecessary allocations. Use when writing new code, distinct from profiling existing slow code (use profiling-analysis for that). license: MIT
This skill teaches the philosophy of writing efficient code by default through non-pessimization - avoiding unnecessary work rather than adding "optimizations" on top of bloated code.
Three Philosophies of Optimization
1. Real Optimization
Benchmarking, measuring, comparing to theoretical maximum, profiling hot paths, reading assembly. This is expensive and rarely needed. Only do this after non-pessimization.
2. Non-Pessimization
The default approach. Write the simplest code that works without introducing unnecessary work. Don't copy data unnecessarily. Don't allocate in hot paths. Don't touch data more than necessary. This gives 100-1000x improvements with minimal effort.
3. Fake Optimization
Repeating heard advice without understanding or measurement. "Arrays are faster than linked lists." "Custom memcopy is faster." These are non-statements. Avoid.
"The degree to which we're able to actually use the computer hardware we have to solve the problems we're trying to solve is at an all-time low." — Casey Muratore
The Core Principle
What is the minimum amount of work required? Type that in.
Ask before every operation:
- Does this need to be copied?
- Does this need to be allocated?
- Does this need to be converted?
- Can this be deferred?
Key Techniques from Ref Term
Don't Copy Data
Keep data in buffers. When data comes in from a pipe, don't copy it into your own structures - work directly on the buffer.
// Bad: Copy incoming data
fn process(data: &[u8]) {
let owned = data.to_vec(); // Copy!
// work with owned...
}
// Good: Work directly on buffer
fn process(data: &[u8]) {
// work directly on data, no copy
}
Don't Touch Data Multiple Times
When data arrives, process it once and store the result. Don't re-parse, re-scan, or re-process.
// Bad: Re-scan for each render
fn render(&mut self) {
for line in &self.lines {
for char in line.chars() { // Re-parse every frame!
// render...
}
}
}
// Good: Pre-compute and cache
fn parse(&mut self, data: &[u8]) {
// Parse once, store indices
// Store what style/color applies to each position
}
fn render(&mut self) {
// Read pre-computed data
}
Isolate Slow Code Behind Caches
When you must use slow libraries (OS APIs, complex parsers), cache aggressively.
// Bad: Call slow library every time
fn get_glyph(c: char) -> Glyph {
unsafe { slow_uniscribe_font_api(c) } // Terrible!
}
// Good: Cache with LRU
struct GlyphCache {
cache: lru::LruCache<u32, Glyph>,
}
impl GlyphCache {
fn get(&mut self, c: char) -> Glyph {
let hash = self.hash(c);
if let Some(glyph) = self.cache.get(&hash) {
return *glyph;
}
let glyph = unsafe { slow_uniscribe_font_api(c) };
self.cache.put(hash, glyph);
glyph
}
}
Use Backwards Rendering
Start from pixels and look up what should be there, rather than feeding primitives forward.
// Forward renderer: Iterate primitives, rasterize to pixels
// (GPU does this well, but terminal cells are simpler)
// Backwards renderer: For each pixel, lookup what cell it's in
// This is O(1) per pixel - maximally efficient
fn render_cell(pixel_x: u32, pixel_y: u32) -> Color {
let cell_x = pixel_x / CELL_WIDTH;
let cell_y = pixel_y / CELL_HEIGHT;
let glyph = grid[cell_y][cell_x]; // Direct lookup!
glyph.get_pixel(pixel_x % CELL_WIDTH, pixel_y % CELL_HEIGHT)
}
Use 64-bit Indices for Circular Buffers
Avoid wrapping logic by using absolute indices.
// Bad: Wrapping indices require modulo
struct Buffer {
data: Vec<u8>,
write_idx: usize, // 0..SIZE
}
fn write(&mut self, byte: u8) {
self.data[self.write_idx % SIZE] = byte; // Modulo!
self.write_idx += 1;
}
// Good: 64-bit absolute indices, no wrapping
struct CircularBuffer {
data: Vec<u8>, // Only SIZE bytes
write_idx: u64, // Absolute index, can be 1TB+
}
fn write(&mut self, byte: u8) {
let idx = (self.write_idx % SIZE as u64) as usize;
self.data[idx] = byte;
self.write_idx += 1;
// Old data naturally falls away
}
Direct-Map Common Cases
For hot paths, bypass hash lookups entirely.
// Bad: Hash lookup for everything
fn get_glyph(c: char) -> Glyph {
glyph_cache.lookup(c) // Hash every time
}
// Good: Direct map for ASCII
static ASCII_GLYPHS: [Glyph; 128] = [...];
fn get_glyph(c: char) -> Glyph {
if c as u32 < 128 {
ASCII_GLYPHS[c as usize] // Direct index!
} else {
glyph_cache.lookup(c) // Hash only for complex chars
}
}
Common Pessimizations to Avoid
String Copies
// Bad
fn process(name: &str) -> String {
let s = name.to_string(); // Copy!
// work with s...
}
// Good: Work with &str
fn process(name: &str) {
// work with name directly
}
Allocations in Hot Paths
// Bad
fn hot_path(&mut self) {
let mut temp = Vec::new(); // Allocate!
for item in &self.items {
temp.push(item.value);
}
}
// Good: Pre-allocate or reuse
fn new() -> Self {
Self {
temp: Vec::with_capacity(1000), // Pre-allocate
}
}
fn hot_path(&mut self) {
self.temp.clear(); // Reuse
for item in &self.items {
self.temp.push(item.value);
}
}
Unnecessary Conversions
// Bad
fn process(items: &[Item]) {
let names: Vec<String> = items.iter().map(|i| i.name.clone()).collect();
// work with names...
}
// Good: Work with references
fn process(items: &[Item]) {
for item in items {
// work with &item.name
}
}
Virtual Function Overhead
// Bad: Trait objects in hot paths
trait Renderer {
fn draw(&mut self, shape: &Shape);
}
fn render_all(shapes: &[Shape], renderer: &mut dyn Renderer) {
for shape in shapes {
renderer.draw(shape); // Virtual call each iteration!
}
}
// Good: Monomorphic
fn render_all<T: Renderer>(shapes: &[Shape], renderer: &mut T) {
for shape in shapes {
renderer.draw(shape); // Devirtualized
}
}
// Or: Static dispatch
enum Shape {
Circle(Circle),
Square(Square),
}
fn render_all(shapes: &[Shape]) {
for shape in shapes {
match shape {
Shape::Circle(c) => draw_circle(c),
Shape::Square(s) => draw_square(s),
}
}
}
Unnecessary Object Creation
// Bad
struct Point { x: f32, y: f32 }
fn distance(p1: Point, p2: Point) -> f32 {
((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt()
}
// Good: References
fn distance(p1: &Point, p2: &Point) -> f32 {
((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt()
}
The Isolation Pattern
When you can't avoid slow code, isolate it so it doesn't infect everything else.
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Your Fast │────▶│ Cache │────▶│ Slow Library│
│ Code │ │ │ │ (uniscribe, │
│ │ │ │ │ directwrite)│
└─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌─────────────┐
│ Fast Output │
│ (texture) │
└─────────────┘
- Identify slow code: OS APIs, font rendering, complex parsing
- Add caching layer: Store results, avoid re-entering slow code
- Keep fast path clean: Most data should never touch slow code
When to Use Each Approach
| Scenario | Approach |
|---|---|
| Writing new code | Non-pessimization (default) |
| Hot path identified via profiling | Real optimization |
| Using slow external libraries | Isolate + cache |
| Code review | Check for pessimizations |
| Performance investigation | Profile first, then decide |
The Performance Mindset
- Default to simple: The simplest code is often fastest
- Question assumptions: "That's how we've always done it" is not a reason
- Measure: Don't optimize based on guesses
- Isolate: When you must use slow code, cache it
- Defer: Don't optimize until you know what's slow
"Non-pessimization is the philosophy that says: I'm never going to willingly pile a bunch of code into the CPU that it has to chew through in order to get to the actual work."
Fake Optimization Red Flags
Be skeptical of:
- "X is faster than Y" without context
- "We need a custom allocator"
- "The library caches internally"
- Copy-pasted "optimizations" from blog posts
- Anything that adds complexity without measurement
These are often:
- Context-dependent (true in one case, not another)
- Based on outdated information
- Not actually measured in your codebase
Rule: If you haven't measured it, you don't know if it's faster.
See also: /performance-optimization skill for advanced techniques after non-pessimization is applied.