Understanding memory layout and optimization techniques is crucial for writing high-performance Rust code. This chapter explores how Rust manages memory and how to optimize your programs.
fn memory_demo() {
// Stack allocation: fast, fixed size, automatic cleanup
let x = 42; // i32: 4 bytes on stack
let arr = [1, 2, 3, 4, 5]; // [i32; 5]: 20 bytes on stack
// Heap allocation: slower, dynamic size, manual management
let v = vec![1, 2, 3, 4, 5]; // Vec header on stack, data on heap
let s = String::from("hello"); // String header on stack, data on heap
let b = Box::new(100); // Box pointer on stack, value on heap
println!("Stack value: {}", x);
println!("Heap value: {}", *b);
}
use std::mem::{size_of, align_of};
#[derive(Debug)]
struct Point {
x: f64, // 8 bytes
y: f64, // 8 bytes
}
#[derive(Debug)]
struct Data {
flag: bool, // 1 byte
value: u64, // 8 bytes
count: u32, // 4 bytes
}
fn main() {
println!("Point: {} bytes, align {}", size_of::<Point>(), align_of::<Point>());
// Point: 16 bytes, align 8
println!("Data: {} bytes, align {}", size_of::<Data>(), align_of::<Data>());
// Data: 24 bytes, align 8 (padding added!)
// Optimized version
#[derive(Debug)]
struct OptimizedData {
value: u64, // 8 bytes
count: u32, // 4 bytes
flag: bool, // 1 byte
}
println!("OptimizedData: {} bytes", size_of::<OptimizedData>());
// OptimizedData: 16 bytes (less padding)
}
Order struct fields from largest to smallest to minimize padding:
// Default Rust layout (can be reordered)
#[derive(Debug)]
struct Default {
a: u8,
b: u32,
c: u8,
}
// C-compatible layout (no reordering)
#[repr(C)]
struct CCompat {
a: u8,
b: u32,
c: u8,
}
// Packed (no padding - careful with alignment!)
#[repr(packed)]
struct Packed {
a: u8,
b: u32,
c: u8,
}
fn main() {
println!("Default: {}", std::mem::size_of::<Default>());
println!("C-compat: {}", std::mem::size_of::<CCompat>());
println!("Packed: {}", std::mem::size_of::<Packed>());
}
use std::rc::Rc;
use std::sync::Arc;
fn pointer_sizes() {
println!("Box<i32>: {} bytes", size_of::<Box<i32>>());
// 8 bytes (just a pointer)
println!("Rc<i32>: {} bytes", size_of::<Rc<i32>>());
// 8 bytes (pointer to heap with refcount)
println!("Arc<i32>: {} bytes", size_of::<Arc<i32>>());
// 8 bytes (pointer to heap with atomic refcount)
// Actual heap allocation
let rc = Rc::new(42);
// Heap: [strong_count, weak_count, value]
// [ 4 bytes, 4 bytes, 4 bytes] + padding
println!("Rc strong count: {}", Rc::strong_count(&rc));
}
use std::borrow::Cow;
fn process_text(input: &str) -> Cow<str> {
if input.contains("ERROR") {
// Need to modify: allocate
Cow::Owned(input.replace("ERROR", "WARNING"))
} else {
// No modification: borrow
Cow::Borrowed(input)
}
}
fn main() {
let text1 = "Everything is fine";
let result1 = process_text(text1);
// No allocation!
let text2 = "ERROR occurred";
let result2 = process_text(text2);
// Allocated new string
println!("{}", result1);
println!("{}", result2);
}
// In Cargo.toml:
// [dev-dependencies]
// criterion = "0.5"
//
// [[bench]]
// name = "my_benchmark"
// harness = false
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 => 1,
1 => 1,
n => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn fibonacci_bench(c: &mut Criterion) {
c.bench_function("fib 20", |b| {
b.iter(|| fibonacci(black_box(20)))
});
}
criterion_group!(benches, fibonacci_bench);
criterion_main!(benches);
// Install tools:
// cargo install flamegraph
// Run with profiling:
// cargo flamegraph --bin myapp
// Example code to profile
fn hot_path() {
let mut sum = 0u64;
for i in 0..1_000_000 {
sum = sum.wrapping_add(expensive_calculation(i));
}
println!("Sum: {}", sum);
}
fn expensive_calculation(n: u64) -> u64 {
(0..n).sum()
}
// Bad: allocates every iteration
fn process_bad(items: &[&str]) {
for item in items {
let uppercase = item.to_uppercase(); // Allocation!
println!("{}", uppercase);
}
}
// Better: reuse buffer
fn process_better(items: &[&str]) {
let mut buffer = String::new();
for item in items {
buffer.clear();
buffer.push_str(item);
buffer.make_ascii_uppercase();
println!("{}", buffer);
}
}
// Best: avoid allocation entirely if possible
fn process_best(items: &[&str]) {
for item in items {
print!("{}", item.to_uppercase());
}
}
use smallvec::{SmallVec, smallvec};
fn smallvec_demo() {
// Store up to 4 items inline, then spill to heap
let mut vec: SmallVec<[i32; 4]> = smallvec![1, 2, 3];
// Still on stack
vec.push(4);
// Now spills to heap
vec.push(5);
// Great for frequently-small collections
// Common pattern: SmallVec<[T; 8]>
}
// Slow: intermediate collections
fn sum_squares_slow(nums: &[i32]) -> i32 {
let filtered: Vec<_> = nums.iter().filter(|&&x| x > 0).collect();
let mapped: Vec<_> = filtered.iter().map(|&&x| x * x).collect();
mapped.iter().sum()
}
// Fast: no intermediate allocations
fn sum_squares_fast(nums: &[i32]) -> i32 {
nums.iter()
.filter(|&&x| x > 0)
.map(|&x| x * x)
.sum()
}
// Even faster: use fold directly
fn sum_squares_fastest(nums: &[i32]) -> i32 {
nums.iter()
.filter(|&&x| x > 0)
.fold(0, |acc, &x| acc + x * x)
}
// Portable SIMD (nightly)
#![feature(portable_simd)]
use std::simd::{f32x4, SimdFloat};
fn simd_sum(values: &[f32]) -> f32 {
let mut sum = 0.0;
// Process 4 values at a time
let chunks = values.chunks_exact(4);
let remainder = chunks.remainder();
let mut vec_sum = f32x4::splat(0.0);
for chunk in chunks {
let vec = f32x4::from_slice(chunk);
vec_sum += vec;
}
sum += vec_sum.reduce_sum();
// Handle remainder
sum += remainder.iter().sum::<f32>();
sum
}
// Using packed_simd crate (stable)
// [dependencies]
// packed_simd = "0.3"
use std::cell::RefCell;
struct Pool<T> {
items: RefCell<Vec<T>>,
}
impl<T> Pool<T> {
fn new() -> Self {
Pool {
items: RefCell::new(Vec::new()),
}
}
fn acquire(&self) -> Option<T> {
self.items.borrow_mut().pop()
}
fn release(&self, item: T) {
self.items.borrow_mut().push(item);
}
}
// Usage
fn pool_example() {
let pool = Pool::<Vec<u8>>::new();
// Get a buffer (or allocate new)
let mut buf = pool.acquire().unwrap_or_else(Vec::new);
// Use it
buf.extend_from_slice(b"hello");
// Return it for reuse
buf.clear();
pool.release(buf);
}
// Array of Structures (AoS) - cache unfriendly
struct ParticleAoS {
x: f32,
y: f32,
vx: f32,
vy: f32,
}
fn update_aos(particles: &mut [ParticleAoS]) {
for p in particles {
p.x += p.vx; // Jumps around in memory
p.y += p.vy;
}
}
// Structure of Arrays (SoA) - cache friendly
struct ParticlesSoA {
x: Vec<f32>,
y: Vec<f32>,
vx: Vec<f32>,
vy: Vec<f32>,
}
fn update_soa(particles: &mut ParticlesSoA) {
// Better cache locality
for i in 0..particles.x.len() {
particles.x[i] += particles.vx[i];
particles.y[i] += particles.vy[i];
}
}
# In Cargo.toml [profile.release] lto = true # Link-time optimization codegen-units = 1 # Better optimization, slower compile opt-level = 3 # Maximum optimization strip = true # Remove debug symbols # Profile-guided optimization # 1. Build instrumented binary # RUSTFLAGS="-Cprofile-generate=/tmp/pgo-data" cargo build --release # # 2. Run workload # ./target/release/myapp # # 3. Build optimized binary # RUSTFLAGS="-Cprofile-use=/tmp/pgo-data" cargo build --release
// Compute at compile time
const fn factorial(n: u64) -> u64 {
match n {
0 | 1 => 1,
_ => n * factorial(n - 1),
}
}
const FACT_10: u64 = factorial(10); // Computed at compile time!
fn main() {
println!("10! = {}", FACT_10); // No runtime cost
}
// Const generic computation
fn create_lookup_table<const N: usize>() -> [u64; N] {
let mut table = [0; N];
let mut i = 0;
while i < N {
table[i] = factorial(i as u64);
i += 1;
}
table
}
const FACTORIALS: [u64; 20] = create_lookup_table::<20>();
// Safe but bounds-checked every access
fn sum_safe(data: &[i32]) -> i32 {
let mut sum = 0;
for i in 0..data.len() {
sum += data[i]; // Bounds check on every access
}
sum
}
// Unsafe: skip bounds checks when we know it's safe
fn sum_unsafe(data: &[i32]) -> i32 {
let mut sum = 0;
for i in 0..data.len() {
unsafe {
sum += *data.get_unchecked(i); // No bounds check
}
}
sum
}
// Best: use iterators (no bounds checks, same speed as unsafe)
fn sum_iter(data: &[i32]) -> i32 {
data.iter().sum()
}
Only use unsafe when:
Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.
Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.
Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.