惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
Scott Helme
Scott Helme
爱范儿
爱范儿
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
阮一峰的网络日志
阮一峰的网络日志
博客园 - Franky
V
V2EX
腾讯CDC
博客园_首页
博客园 - 司徒正美
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tailwind CSS Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog
雷峰网
雷峰网
Stack Overflow Blog
Stack Overflow Blog
IT之家
IT之家
罗磊的独立博客
Recorded Future
Recorded Future
博客园 - 聂微东
O
OpenAI News
S
Secure Thoughts
Hacker News: Ask HN
Hacker News: Ask HN
S
Schneier on Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
Y
Y Combinator Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Project Zero
Project Zero
宝玉的分享
宝玉的分享
K
Kaspersky official blog
N
Netflix TechBlog - Medium
T
The Exploit Database - CXSecurity.com
Google Online Security Blog
Google Online Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Webroot Blog
Webroot Blog
云风的 BLOG
云风的 BLOG
Simon Willison's Weblog
Simon Willison's Weblog
C
Check Point Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 热门话题
美团技术团队
L
Lohrmann on Cybersecurity

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Rust's Zero-Cost Abstractions, What Monomorphization Actually Does to Your Code
shayan holak · 2026-04-28 · via DEV Community

"Zero-cost abstractions" is one of Rust's core promises. You can write generic, composable, high-level code and the compiler will produce the same machine code as if you had written the low-level version by hand. Most people accept this claim and move on. It is worth actually understanding the mechanism behind it, because it has real consequences for compile times, binary size, and performance in ways that will eventually surprise you.

The Problem Abstractions Usually Create

In most languages with generics or polymorphism, the runtime pays for flexibility. Java's generics are erased at compile time and everything becomes Object, which means heap allocation and virtual dispatch. Python functions accept anything but pay for it with dynamic type lookups on every operation. Even C++ with templates avoids runtime cost, but the mechanism it uses is the same one Rust uses.

The question is: how do you write one function that works on many types, without inserting a layer of indirection at runtime?

What Monomorphization Is

Monomorphization means the compiler generates a separate, concrete copy of a generic function for each type it is actually called with. You write one function. The compiler writes many.

fn largest<T: PartialOrd>(a: T, b: T) -> T {
    if a > b { a } else { b }
}

fn main() {
    largest(1i32, 2i32);
    largest(1.0f64, 2.0f64);
}

Enter fullscreen mode Exit fullscreen mode

After monomorphization, the compiler has effectively produced this:

fn largest_i32(a: i32, b: i32) -> i32 {
    if a > b { a } else { b }
}

fn largest_f64(a: f64, b: f64) -> f64 {
    if a > b { a } else { b }
}

Enter fullscreen mode Exit fullscreen mode

Each version is fully concrete. The CPU never sees a generic type. There is no branching on type, no vtable lookup, no boxing. The generated assembly for largest_i32 is exactly what you would get if you had written it for i32 from the start.

You can verify this yourself. Run cargo build --release and inspect the output with cargo-show-asm or objdump. Each monomorphized version shows up as a distinct symbol in the binary.

How Traits Fit Into This

Traits are the constraint mechanism. When you write T: PartialOrd, you are telling the compiler what operations are available on T. At the call site, the compiler knows the concrete type, so it knows the exact implementation of PartialOrd to use. It inlines it directly.

This is what makes iterator chains fast:

let sum: i32 = (0..1000)
    .filter(|x| x % 2 == 0)
    .map(|x| x * x)
    .sum();

Enter fullscreen mode Exit fullscreen mode

Each of filter, map, and sum is generic over the iterator type. After monomorphization, the entire chain collapses into a single loop with no intermediate allocation and no function call overhead. The compiler sees through every layer. It knows the concrete type at each step because you started with Range<i32>, and each adapter wraps the previous one in a new concrete type.

Compare this to how you would write the equivalent in a language without monomorphization. You would either materialize an intermediate collection at each step, or you would use some form of dynamic dispatch with its associated overhead.

The Actual Cost: Code Bloat and Compile Time

Zero-cost at runtime does not mean zero-cost overall. You pay elsewhere.

Binary size. Every unique combination of generic function and concrete type produces a new copy in the binary. If you call Vec::new::<String>(), Vec::new::<i32>(), and Vec::new::<MyStruct>(), you get three copies of the Vec::new implementation. In a large codebase with many generic types, this adds up. It is a real concern for embedded targets and WebAssembly where binary size matters.

Compile time. Monomorphization happens during code generation, which is one of the most expensive phases of Rust compilation. Every unique instantiation of a generic function is work the compiler has to do. This is a significant contributor to Rust's notoriously slow compile times. When you see a crate that takes thirty seconds to compile, a large part of that is the code generation phase expanding generics.

Instruction cache pressure. Multiple copies of similar functions means more machine code in memory. If those functions are all hot paths called in rapid succession, you can end up with instruction cache misses that would not exist with a single shared implementation.

Static Dispatch vs Dynamic Dispatch

Monomorphization is static dispatch. The call target is resolved at compile time. Rust also supports dynamic dispatch through trait objects, and the tradeoff is exactly what you would expect.

// static dispatch: monomorphized, zero runtime overhead
fn process_static<T: Draw>(item: T) {
    item.draw();
}

// dynamic dispatch: single function, vtable lookup at runtime
fn process_dynamic(item: &dyn Draw) {
    item.draw();
}

Enter fullscreen mode Exit fullscreen mode

With &dyn Draw, the compiler generates one function. At runtime, a vtable pointer accompanies the reference, and the call goes through an indirect jump. This costs roughly one extra memory lookup per call. In exchange, you get a single copy of process_dynamic in the binary, and you can put different concrete types into the same collection.

The practical rule: use static dispatch (generics) for performance-critical code where all types are known at compile time. Use dynamic dispatch (dyn Trait) when you need heterogeneous collections, when the concrete type is only known at runtime, or when binary size and compile time matter more than the last bit of call overhead.

Where Monomorphization Gets Interesting: Trait Objects in Generic Contexts

A subtlety that catches people: trait objects themselves can be used as concrete types in generic contexts, which then get monomorphized.

fn process<T: Draw>(items: Vec<T>) { ... }

// This is one monomorphization
process::<Box<dyn Draw>>(vec![...]);

Enter fullscreen mode Exit fullscreen mode

Here T is Box<dyn Draw>. The function is monomorphized for that concrete type. Inside the function, calls through T still go through the vtable because T is a trait object. You have static dispatch to the function, and dynamic dispatch inside it. Understanding this layering matters when you are trying to reason about where the overhead actually lives.

The impl Trait Shorthand

impl Trait in argument position is syntactic sugar for a generic parameter:

// these are equivalent
fn process(item: impl Draw) { ... }
fn process<T: Draw>(item: T) { ... }

Enter fullscreen mode Exit fullscreen mode

Both are monomorphized. Each unique concrete type passed to process produces a new instantiation. impl Trait is not dynamic dispatch despite looking less generic at first glance.

impl Trait in return position is different:

fn make_drawable() -> impl Draw {
    Circle::new()
}

Enter fullscreen mode Exit fullscreen mode

This tells the caller "you will get something that implements Draw, but I am not telling you the concrete type." The concrete type is fixed at compile time and the function is not generic over it. The caller cannot name the type but the compiler knows it, so there is no dynamic dispatch. It is a way to hide implementation details while keeping static dispatch.

Inspecting the Output

The best way to build intuition for what monomorphization produces is to look at actual assembly. The cargo-show-asm tool makes this straightforward:

cargo install cargo-show-asm
cargo asm --release your_crate::your_function

Enter fullscreen mode Exit fullscreen mode

Run it on a generic function called with two different types and you will see two separate assembly listings with distinct symbol names. Run it on the iterator chain example and you will see a tight loop with no function calls. The gap between what you wrote and what the CPU executes is much smaller in Rust than in most languages, and this tool makes that concrete rather than theoretical.

The Mental Model to Carry Forward

When you write generic Rust code, think of yourself as writing a template that the compiler will stamp out once per concrete type. Each stamp is as fast as hand-written code for that type. The tradeoff you are making is compilation time and binary size in exchange for runtime performance and the ability to write the logic once.

This is why Rust can match C performance while supporting generics, iterators, and trait-based abstractions. The abstraction cost is paid at compile time, not runtime. Zero-cost does not mean free. It means the cost is moved to a place where it hurts less.

Further Reading