Chapter 3 of 16 · Part I, Foundations
Where your data actually lives
Where Rust values live compared with C# class and struct: Box, String against &str, memory layout, padding, niche optimization and the C# habits to drop.
You will learn to distinguish a value from the allocation it may own, and an owned string from a borrowed view. Read through the owned and borrowed pairs first. The size measurements, padding, and niche optimization sections can wait until that distinction is comfortable.
In C#, a class is a reference type: a variable holds a reference to an object. A struct is a value type: its data is stored inline wherever the value itself lives, such as in a containing object or array. A local value is not guaranteed a physical stack slot; the runtime can keep it in a register or optimize it away. Boxing a struct creates a boxed object containing a copy.
Rust's struct is a value type. You can store the same type inline or put it behind an owning pointer such as Box at a particular use site:
let on_stack = Server { hostname: String::from("db-1"), port: 5432 };
let on_heap = Box::new(Server { hostname: String::from("db-1"), port: 5432 });
That is the whole idea, and most of this chapter is consequences of it.
One kind of struct, and what that costs
When you write class in C#, you are asking for several things at once and you probably do not separate them in your head, because you never had to.
You are asking for heap allocation. You are asking for reference semantics, so that assigning the variable copies an address and two variables see one object. You are asking for reference identity, so ReferenceEquals means something. You are asking for nullability, because a reference can be absent. Depending on the class and its members, you can also use inheritance and virtual dispatch. And you are asking the GC to track it.
Rust unbundles those. A struct is a value with a size and a layout, and nothing else. Then:
- heap allocation is
Box::new - shared reference semantics are
&T, orRc<T>when the sharing has to outlive a single scope - absence is
Option<T> - virtual dispatch is
dyn Trait - identity is an address you can compare when you have a reason to, with
Rc::ptr_eqorstd::ptr::eq - ordinary owned values are dropped at their drop points; Rust does not require a tracing collector
- there is no inheritance, and the answer is composition plus traits
The practical effect is that the same type can live in different places in different functions. A Reading can sit inline in a Vec in the ingest path, be passed by reference to a validator, and be boxed once when it goes into a heterogeneous queue. You do not need three types for that. You need one type and three use sites.
The cost is that you now think about indirection every time you write a signature. In C# you write Customer in a parameter list and the language has already decided what that means. In Rust you write Customer, &Customer, &mut Customer, or Box<Customer>, and each is a different contract. That is four options where the language used to hand you one, and for the first month it is genuinely slower.
Box, and the struct that contains itself
Box<T> is the simplest owning pointer. For a non-zero-sized value, it normally owns one heap allocation, which is released when the box is dropped. Zero-sized values do not require an allocation. It is documented as the most straightforward form of heap allocation in the language, and that is exactly what it is: new without a collector attached.
Here are four common reasons to reach for it.
The first is a type that contains itself. In C#, a class holding a field of its own type is unremarkable, because the field is a reference and every reference is one word:
class Node
{
public int Value;
public Node Next; // one word, may be null
}
Write the direct translation in Rust and the compiler stops you:
struct Node {
value: i32,
next: Option<Node>,
}
error[E0072]: recursive type `Node` has infinite size
--> src/main.rs:1:1
|
1 | struct Node {
| ^^^^^^^^^^^
2 | value: i32,
3 | next: Option<Node>,
| ---- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
3 | next: Option<Box<Node>>,
| ++++ +
The error is not a rule the designers made up. It is arithmetic that has no solution. The compiler computes the size of Node as the size of value plus the size of next, and the size of next depends on the size of Node. There is no fixed point. Any layout you propose is four bytes too small.
C# never hits this because the field is not a Node, it is a reference to a Node, and a reference is typically eight bytes on the x64 runtime used in the examples below. The indirection was always there. You just did not type it. Box is you typing it.
On the x86_64 Rust toolchain measured below, the fixed Node is 16 bytes: eight for the pointer, four for the i32, and four of padding. The precise default struct layout is not a portable guarantee. The error code page covers the general form.
The second situation is a value whose size is not known at compile time. dyn Trait and [T] are unsized, so they cannot be stored in a local or a field directly. Box<dyn Error> is the workhorse example, and unsized types get their own reference chapter because the rules are subtle.
The third is a value large enough that moving it around costs real bytes. For a sized value on a typical 64-bit target, a Box is pointer-sized. Moving the box transfers ownership of that pointer; moving a value may involve copying its bytes, although the optimizer can often eliminate the copy. If a struct is a few hundred bytes and you pass it up through five call frames, boxing it once is a fair trade, although the optimizer often removes the copies anyway.
The fourth is when an allocation's address matters, as in some FFI or intrusive data structures. Moving a Box does not by itself relocate its allocation, but the value can still be moved out of an ordinary box. When correctness requires a value not to move, look at Pin<Box<T>> and its guarantees.
These are examples, not an exhaustive list. Notice what is not on it: "because I would have used a class in C#." Boxing every struct out of habit is a week-one reflex, and it produces Rust that allocates more than the C# it replaced.
The first model was too simple
The model so far: a value lives where you put it, a local is on the stack, Box is the heap. Good enough to write code with, and not quite what happens.
What is actually true is narrower. size_of tells you the size a value occupies when the compiler has to give it a place: inside a struct, inside an array, or when it crosses a function boundary that was not inlined. It does not promise the value is ever written to memory at all. A Reading that you construct, read one field from, and drop may spend its entire life in registers, with no stack slot allocated for it. LLVM decides that, not the type system.
The same applies to moves. When you hand a String to a function, the model says twenty-four bytes are copied from one stack slot to another. In a release build with inlining, frequently nothing is copied because there was only ever one slot. The move is a fact about ownership, which the next chapter is about, and only sometimes a fact about memcpy.
Read the sizes below as observations for the named target and compiler, plus any guarantees the documentation explicitly gives. Default Rust layout can change, and a measured size is not a promise about instructions. Those are different claims, and conflating them is how people end up micro-optimizing a struct that the optimizer had already deleted.
Two strings, and why
The part that trips people up first is that Rust has two string types you will meet in the first hour.
String is an owned, growable, heap-allocated UTF-8 buffer. It is List<byte> shaped, with a UTF-8 guarantee the type enforces on every path in. &str is a borrowed view into UTF-8 bytes that somebody else owns. A string literal in your source is a &'static str, pointing into the read-only data of the binary itself.
let owned: String = String::from("db-1.internal");
let borrowed: &str = &owned; // a view, no allocation
let literal: &str = "db-1.internal"; // points into the binary
The closest thing in your existing model is string versus ReadOnlySpan<char>. String owns and can grow. &str is a pointer and a length, cannot grow, and cannot outlive what it points at.
A useful convention follows: take &str when a function only needs to read text, and return String when it creates owned text. Callers can borrow a String or pass a string slice without allocating for the argument.
fn is_internal(host: &str) -> bool {
host.ends_with(".internal")
}
Now the encoding, which is the real difference from .NET and the one that changes how you write code.
A .NET string is a sequence of UTF-16 code units. Length counts code units, s[i] returns a char, and a char is sixteen bits. That design dates from a time when Unicode fit in sixteen bits and the encoding looked fixed-width. It stopped being fixed-width when Unicode went past U+FFFF, and the repair was surrogate pairs: two char values that together mean one character. Microsoft's encoding introduction is direct about this, and System.Text.Rune exists because char alone cannot represent every scalar value.
Rust made the other choice. String and str are guaranteed to hold valid UTF-8, always, enforced by the type. A Rust char is a Unicode scalar value and is four bytes. It can represent a scalar value without surrogate pairs, although one user-perceived character can consist of multiple scalar values.
The reason is boundaries. Many service interfaces use UTF-8, including common JSON and text payloads. Converting those bytes into a .NET string and encoding that string back to UTF-8 requires transcoding, but not every service needs to convert every byte: both ecosystems offer byte-oriented APIs. Whether the conversion matters depends on the workload, so measure it on the path you care about. Linux file names are bytes and need not be valid UTF-8.
You pay for that guarantee in a different currency, and the bill arrives the first time you try to index a string.
Why you cannot index a string by position
The direct translation of the most ordinary line in C# does not compile:
string host = "db-1.internal";
char first = host[0]; // fine, O(1)
let host = String::from("db-1.internal");
let first = host[0];
error[E0277]: the type `str` cannot be indexed by `{integer}`
--> src/main.rs:3:22
|
3 | let first = host[0];
| ^ string indices are ranges of `usize`
|
= help: the trait `SliceIndex<str>` is not implemented for `{integer}`
= note: you can use `.chars().nth()` or `.bytes().nth()`
for more information, see chapter 8 in The Book: <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>
note: required for `String` to implement `Index<{integer}>`
The mechanism is worth having straight, because the same reasoning turns up again in get, in the slicing rules, and in why iteration is the default way to walk text.
In UTF-8, characters are one to four bytes. Byte number seven is not character number seven. So host[7] has two possible meanings, and both are bad. If it returns a byte, the type is u8 and you have handed the caller a fragment of a character with no warning. That is the same bug UTF-16 indexing produces in .NET, with a different trigger: an accented Latin letter is a single UTF-16 code unit and behaves fine, so the failure waits for something above U+FFFF, an emoji or a rarer CJK character, where s[i] hands you a lone surrogate half. If it returns a char, the operation is O(n), because finding the seventh character means walking from the start, and Rust will not give an O(n) operation the syntax of an O(1) one.
So it refuses, and the note tells you which one you meant. The Book's chapter on strings works through the same argument at length.
Range slicing does work, because a range is a pair of byte offsets and you are explicitly saying you know where the boundaries are. If you are wrong, it panics rather than producing mojibake:
let s = "naïve";
println!("{}", &s[0..3]);
thread 'main' panicked at src/main.rs:3:22:
end byte index 3 is not a char boundary; it is inside 'ï' (bytes 2..4 of string)
That panic is a design choice you should notice. Slicing a string at a byte offset you got from somewhere trustworthy is fast and common. Slicing at an offset you made up is a bug, and Rust would rather crash the request than corrupt the data.
What you use instead, depending on what you actually meant:
| You wanted | Rust |
|---|---|
| the nth character | s.chars().nth(n), and know it is O(n) |
| the nth byte | s.as_bytes()[n] |
| character positions with byte offsets | s.char_indices() |
| a substring by known byte range | &s[start..end] |
| a substring, fallibly | s.get(start..end), returns an Option |
| find and cut | s.find('.') then slice at the returned offset |
The comparison worth sitting with. First the C#, which compiles and is wrong:
string s = "a\U0001F980b"; // a, crab, b
Console.WriteLine(s.Length); // 4, because the crab is two code units
Console.WriteLine(s[1]); // a lone high surrogate, prints as garbage
And the Rust, which is uglier and correct:
let s = "a🦀b";
println!("{}", s.len()); // 6, bytes
println!("{}", s.chars().count()); // 3, characters
println!("{:?}", s.chars().nth(1)); // Some('🦀')
Both operations can be useful when you know what they count. A UTF-16 code unit is not necessarily a user-perceived character, and neither is a Rust char; choose the unit the task needs.
The owned and borrowed pairs
The String and &str split is not a special case for text. It is a pattern the whole standard library follows, and once you see it the library stops looking arbitrary.
| Owns the buffer | Borrows a view | Notes |
|---|---|---|
String | &str | UTF-8 guaranteed on both |
Vec<T> | &[T] | the array case |
PathBuf | &Path | platform-native path bytes |
OsString | &OsStr | OS strings, not guaranteed UTF-8 |
CString | &CStr | nul-terminated, for FFI |
Box<T> | &T | the general case |
The owned type is a value you can move, grow, and drop. The borrowed type is a pointer with no ownership and a lifetime attached, fat when the thing it points at is unsized and thin when it is not. Functions take the borrowed form, constructors and builders return the owned form.
The reason &owned works where &str is expected, and &my_vec works where &[T] is expected, is deref coercion: the compiler will insert a Deref call to turn &String into &str at a call site. It does not go the other way, which is why the most common early error is this one:
error[E0308]: mismatched types
--> src/main.rs:7:32
|
7 | println!("{}", is_internal(owned));
| ----------- ^^^^^ expected `&str`, found `String`
| |
| arguments to this function are incorrect
|
note: function defined here
--> src/main.rs:1:4
|
1 | fn is_internal(host: &str) -> bool {
| ^^^^^^^^^^^ ----------
help: consider borrowing here
|
7 | println!("{}", is_internal(&owned));
| +
The fix is one ampersand, and the compiler tells you exactly where to put it. Add the ampersand. Do not add .clone().
Slices deserve one more paragraph because they are the piece with the closest .NET analogue. A &[T] is an address plus a length, and it can point at a Vec, at a fixed-size array, or at part of either. The slice primitive has the whole surface. A function taking &[f64] accepts all three callers without allocating:
fn mean(samples: &[f64]) -> f64 {
if samples.is_empty() { return 0.0; }
samples.iter().sum::<f64>() / samples.len() as f64
}
fn main() {
let owned: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];
let fixed: [f64; 3] = [10.0, 20.0, 30.0];
assert_eq!(mean(&owned), 2.5); // Vec
assert_eq!(mean(&fixed), 20.0); // fixed-size array
assert_eq!(mean(&owned[1..3]), 2.5); // part of a Vec
}
Span<T> is the same shape and exists for the same reason. The difference is that Span<T> had to be a ref struct with a list of restrictions bolted on, because C# had no way to express "this must not outlive the thing it points at" in the general type system. In Rust, &[T] is an ordinary type. The lifetime rule is not a special case for slices, it is how every reference works, so slices needed no new machinery.
What things actually cost
std::mem::size_of reports the size of a type in bytes, align_of reports its alignment, and offset_of!, stable since Rust 1.77, reports where a field landed. Reading a few of these is the fastest way to build intuition. Here is a complete program you can paste into a file and run.
#![allow(dead_code)]
use std::mem::{align_of, offset_of, size_of};
use std::num::NonZeroU32;
struct Reading {
timestamp: i64,
value: f64,
sensor_id: i32,
valid: bool,
}
// Declared worst-first on purpose.
struct Ragged {
flag: bool,
id: u64,
kind: u8,
}
// Same fields, C rules, no reordering allowed.
#[repr(C)]
struct RaggedC {
flag: bool,
id: u64,
kind: u8,
}
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn row(name: &str, size: usize, align: usize) {
println!("{:<20} {:>3} {:>2}", name, size, align);
}
fn main() {
println!("{:<20} {:>3} {:>2}", "type", "size", "align");
row("i32", size_of::<i32>(), align_of::<i32>());
row("f64", size_of::<f64>(), align_of::<f64>());
row("bool", size_of::<bool>(), align_of::<bool>());
row("char", size_of::<char>(), align_of::<char>());
row("()", size_of::<()>(), align_of::<()>());
row("&i32", size_of::<&i32>(), align_of::<&i32>());
row("Box<i32>", size_of::<Box<i32>>(), align_of::<Box<i32>>());
row("Option<Box<i32>>", size_of::<Option<Box<i32>>>(), align_of::<Option<Box<i32>>>());
row("Option<&i32>", size_of::<Option<&i32>>(), align_of::<Option<&i32>>());
row("Option<i32>", size_of::<Option<i32>>(), align_of::<Option<i32>>());
row("Option<NonZeroU32>", size_of::<Option<NonZeroU32>>(), align_of::<Option<NonZeroU32>>());
row("Option<bool>", size_of::<Option<bool>>(), align_of::<Option<bool>>());
row("&str", size_of::<&str>(), align_of::<&str>());
row("&[u8]", size_of::<&[u8]>(), align_of::<&[u8]>());
row("String", size_of::<String>(), align_of::<String>());
row("Vec<u8>", size_of::<Vec<u8>>(), align_of::<Vec<u8>>());
row("Reading", size_of::<Reading>(), align_of::<Reading>());
row("Node", size_of::<Node>(), align_of::<Node>());
println!();
println!("Ragged size {:>2} flag@{} id@{} kind@{}",
size_of::<Ragged>(),
offset_of!(Ragged, flag), offset_of!(Ragged, id), offset_of!(Ragged, kind));
println!("RaggedC size {:>2} flag@{} id@{} kind@{}",
size_of::<RaggedC>(),
offset_of!(RaggedC, flag), offset_of!(RaggedC, id), offset_of!(RaggedC, kind));
println!();
let host = String::from("db-1.internal");
println!("\"{}\" len {} chars {}", host, host.len(), host.chars().count());
let emoji = "a🦀b";
println!("\"{}\" len {} chars {}", emoji, emoji.len(), emoji.chars().count());
println!("byte offsets: {:?}", emoji.char_indices().collect::<Vec<_>>());
}
On stable Rust 1.98, x86_64, that prints:
type size align
i32 4 4
f64 8 8
bool 1 1
char 4 4
() 0 1
&i32 8 8
Box<i32> 8 8
Option<Box<i32>> 8 8
Option<&i32> 8 8
Option<i32> 8 4
Option<NonZeroU32> 4 4
Option<bool> 1 1
&str 16 8
&[u8] 16 8
String 24 8
Vec<u8> 24 8
Reading 24 8
Node 16 8
Ragged size 16 flag@9 id@0 kind@8
RaggedC size 24 flag@0 id@8 kind@16
"db-1.internal" len 13 chars 13
"a🦀b" len 6 chars 3
byte offsets: [(0, 'a'), (1, '🦀'), (5, 'b')]
Go through the interesting rows.
char is four bytes, not one and not two. It holds a scalar value, so it needs twenty-one bits and gets thirty-two. A .NET char is two bytes and cannot hold the crab on its own.
() is zero bytes. The unit type is Rust's void with the difference that it is a real type you can put in a generic parameter, which is why Result<(), E> is the signature of a function that can fail and returns nothing useful. HashSet<T> is a HashMap with zero-sized values, and the map genuinely stores nothing for them.
String and Vec<u8> are both twenty-four bytes: pointer, length, capacity. A .NET List<T> tracks roughly the same thing, an array reference and a count, with capacity implied by the array's own length. This is where the layouts diverge. In Rust those twenty-four bytes are the value. They sit in your stack frame, or inline inside the containing struct, and there is one heap allocation, for the elements. In .NET you have a reference on the stack, a List<T> object on the heap with a header and a method table pointer, and a separate array object on the heap with its own header. One more allocation, and one more pointer hop on the way to any element.
&str and &[u8] are sixteen: address plus length.
Reading is twenty-four. Eight for the i64, eight for the f64, four for the i32, one for the bool, three of padding to reach a multiple of the eight-byte alignment.
Alignment, padding, and why the compiler moves your fields
Alignment is a hardware constraint that leaks into the type system. A type with alignment eight must start at an address divisible by eight, because that is what the load and store instructions want. Structs inherit the largest alignment of their fields, and the compiler inserts padding bytes to keep every field aligned and to make the struct's own size a multiple of its alignment, so that consecutive elements in an array stay aligned.
Padding is why field order matters. Ragged declares a bool, then a u64, then a u8. Laid out in declaration order: one byte, seven of padding, eight, one, seven more of padding. Twenty-four bytes for ten bytes of data.
Rust does not lay it out in declaration order. The default representation makes no guarantee about field order. In this example, rustc has reordered the fields and reduced padding; neither that order nor a minimal size is guaranteed. The output shows id at offset 0, kind at 8, flag at 9, and six bytes of tail padding. Sixteen bytes. A third smaller, for free, because you were not promised an order in the first place. The Rustonomicon's chapter on repr(Rust) walks through the same example.
Write #[repr(C)] and you opt into the C rules, which do promise declaration order, and you get twenty-four bytes back. That can be useful for C interoperability and other cases needing a defined C-compatible layout. It is not by itself a portable wire format: endianness, padding, field validity, and nested representations still matter. The reference section on the C representation is the spec.
Now the C# side, which does not go the way most people assume. The same struct, plus two variations worth having in the same output:
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
struct A { public bool Flag; public ulong Id; public byte Kind; } // declared badly
struct B { public ulong Id; public bool Flag; public byte Kind; } // declared well
[StructLayout(LayoutKind.Auto)]
struct AutoA { public bool Flag; public ulong Id; public byte Kind; }
class ClassA { public bool Flag; public ulong Id; public byte Kind; }
class ClassB { public ulong Id; public bool Flag; public byte Kind; }
class LayoutProbe
{
static unsafe void Main()
{
Console.WriteLine($"A = {Unsafe.SizeOf<A>()} (default struct layout)");
Console.WriteLine($"B = {Unsafe.SizeOf<B>()} (default struct layout)");
Console.WriteLine($"AutoA = {Unsafe.SizeOf<AutoA>()} (LayoutKind.Auto)");
Console.WriteLine($"A is sequential: {typeof(A).IsLayoutSequential}");
A a = default;
Console.WriteLine($"A offsets: Flag {(byte*)&a.Flag - (byte*)&a}, " +
$"Id {(byte*)&a.Id - (byte*)&a}, " +
$"Kind {(byte*)&a.Kind - (byte*)&a}");
long m0 = GC.GetAllocatedBytesForCurrentThread();
var ca = new ClassA();
long m1 = GC.GetAllocatedBytesForCurrentThread();
var cb = new ClassB();
long m2 = GC.GetAllocatedBytesForCurrentThread();
GC.KeepAlive(ca); GC.KeepAlive(cb);
Console.WriteLine($"ClassA = {m1 - m0}, ClassB = {m2 - m1} (auto layout)");
}
}
That needs AllowUnsafeBlocks. On .NET 9.0.10, x64, it prints:
A = 24 (default struct layout)
B = 16 (default struct layout)
AutoA = 16 (LayoutKind.Auto)
A is sequential: True
A offsets: Flag 0, Id 8, Kind 16
ClassA = 32, ClassB = 32 (auto layout)
The reason A stayed at twenty-four is not that the runtime looked at it and declined to help. It is that the field order was never up for negotiation. The C# compiler stamps LayoutKind.Sequential on structs by default, which the StructLayoutAttribute documentation states plainly: C#, Visual Basic and C++ apply sequential layout to structures by default, and for classes you have to ask for it explicitly. Sequential means declaration order, so declaring the fields badly cost eight bytes per instance and declaring them well got the eight bytes back.
Ask for auto layout on the struct and the packing arrives: AutoA has the bad declaration order and comes out at sixteen. Classes get auto layout without asking, which is why ClassA and ClassB are both thirty-two bytes, sixteen of object overhead plus ten bytes of fields rounded up to the allocation granularity, with the declaration order making no difference at all.
So the defaults are inverted relative to where the pain is. In C# the type most likely to be held by the million, the struct in an array, is the one that keeps your declaration order and your padding. Rust reorders by default and asks you to opt out with #[repr(C)]. In a struct with a dozen fields of mixed width, nobody keeps the ordering optimal by hand across three years of maintenance, and only one of these two languages makes that a non-issue by default.
Niche optimization, or why an optional Box is one word
Option<Box<i32>> is eight bytes. So is Option<&i32>. Option<bool> is one. Option<NonZeroU32> is four. But Option<i32> is eight, when the payload is only four.
The mechanism is called niche optimization. A niche is a bit pattern that the payload type can never hold. If the compiler can find one, it stores the None case there instead of adding a separate discriminant field.
Box and & can never be null, so the null address is a niche, and None is the null pointer. That is more than an optimization the compiler happens to do. It is a documented guarantee: Option<Box<U>> has the same size, alignment, and calling convention as Box<U> when U is sized.
bool uses two bit patterns out of two hundred and fifty six, so there are 254 spare ones and None gets one of them. NonZeroU32 cannot be zero, so zero is free. The standard library also documents the same-size guarantee for Option<NonZeroU32>. The Option<bool> size shown here is an observation of this compiler and target, not a general promise for every Option<T>.
i32 uses every one of its four billion patterns for a real value. There is no niche. So the compiler adds a discriminant byte, giving five bytes, then rounds up to the four-byte alignment, giving eight. The output above shows exactly that: size 8, align 4.
This is why "Rust has no null" costs you nothing at the representation level. The type is checked, you cannot dereference an Option without handling None, and the machine code is a nullable pointer. You get the compile-time guarantee for free.
The comparison in C# is instructive because C# does this twice, differently. Nullable<T> for value types is a struct with a bool HasValue and a T Value, so int? costs eight bytes for the same reason Option<i32> does. Nullable reference types, added in C# 8, work the other way: the annotations are recorded in metadata so other assemblies can read them, but they have no runtime representation, the checking is compiler flow analysis that produces warnings, and a caller from an assembly that never opted in can hand you a null anyway. Rust's Option is one mechanism that covers both cases, is enforced rather than warned about, and is free where a niche exists.
The general layout rules are in the type layout reference, which is the document to reach for when a size surprises you.
A million of them
Take a record you would actually hold a lot of.
class Reading
{
public long Timestamp;
public double Value;
public int SensorId;
public bool Valid;
}
On x64, a CoreCLR object has an eight-byte header word ahead of the reference and an eight-byte method table pointer at it. The runtime source spells this out: on 64-bit targets the object header is a four-byte sync block value plus four bytes of alignment padding, the object itself starts with the method table pointer, and the minimum object size works out to twenty-four bytes.
So the arithmetic for one Reading is sixteen bytes of overhead plus eight plus eight plus four plus one, which is thirty-seven, rounded up to forty. A Reading[] of a million is the array object itself, twenty-four bytes of header plus a million eight-byte references, plus a million forty-byte objects.
array: 24 + 8,000,000 = 8,000,024
objects: 1,000,000 x 40 = 40,000,000
total = 48,000,024 (about 48 MB)
You can check that instead of trusting it. GC.GetAllocatedBytesForCurrentThread reports allocation exactly, and reading it either side of a single new Reading() on .NET 9.0.10, x64, gives forty bytes. Reading it either side of the array and the million objects gives 48,000,056, which is the arithmetic plus a few dozen bytes of noise from the loop itself.
The Rust equivalent is a Vec<Reading> where Reading is twenty-four bytes. One allocation. Twenty-four million bytes. In this example the element storage is about half the size and contiguous. That can improve locality, but actual cache misses and throughput depend on the access pattern and hardware.
The part that does not show up in the byte count is the GC. Those million objects are a million entries the collector has to mark. Rust has zero objects there, because a Vec<Reading> is one allocation as far as the allocator is concerned, and nothing traces it.
Now the honest half. Change the C# to a struct:
struct Reading { public long Timestamp; public double Value; public int SensorId; public bool Valid; }
A Reading[] of a million is then 24,000,024 bytes on the same counter, twenty-four bytes of array header plus a million twenty-four-byte values. For these measured layouts, the element storage is the same size and contiguous, with one array allocation for the records. Similar layout can help locality, but it does not guarantee identical cache behavior.
So the gap is not between the languages. It is between reference layout and value layout, and C# gives you both. What C# does not give you is the ability to pick per use site. Once Reading is a struct, conversions to object or an interface can box it, adding an allocation and a copy; generic APIs and constrained calls can often avoid boxing. Once it is a class, the array is forty megabytes everywhere, including the one hot path where you needed it not to be. Rust's Reading is twenty-four bytes in the Vec and eight bytes in the Box<Reading> in the queue, and it is the same type in both places.
At a hundred readings this is a rounding error and you should not think about it. At a million per host, on a fleet where resident memory is the budget you are actually measured against, it is the difference between one instance size and the next one up.
The mistakes that come from C# habits
Boxing everything. The class reflex says heap. Write Box<Server> in a field and you have added an allocation and a pointer hop for nothing. Symptom: Box in a struct definition where the inner type has a known size and is not recursive. Fix: delete the Box. If you needed sharing rather than heap placement, you wanted &, or Rc if the sharing outlives a scope.
String in every parameter. Coming from string, you write fn handle(host: String), and now every caller has to give up ownership or call .to_string(). Symptom: .to_string() or .clone() at call sites, on values the callee only reads. Fix: take &str. The rule of thumb is take the borrowed form, return the owned form, and only take the owned form when you genuinely keep the value.
Reaching for .clone() when the compiler complains about String versus &str. The E0308 above is a type mismatch whose fix is a borrow, and the compiler's suggestion is a single ampersand. Cloning silences it and allocates. Symptom: .clone() appearing right after you added a function. Fix: read the help line, which tells you where the ampersand goes.
Treating .len() as a character count. It is bytes. "café".len() is five. Symptom: off-by-a-few bugs that only appear for non-ASCII input, which in practice means a support ticket from a customer with an accent in their name. Fix: .chars().count() if you meant characters, and be aware it is O(n) and still not grapheme clusters.
Slicing at an offset you computed with character arithmetic. &s[..10] for a truncation panics on the wrong input. Symptom: a panic saying "is not a char boundary". Fix: get offsets from char_indices, find, or the byte positions the parser gave you, or use s.get(..10) and handle the None.
Reaching for #[repr(C)] because it sounds faster. It provides a C-compatible representation, not an automatic speedup. Its fixed ordering can use more or less space than a particular default layout; measure the target. Symptom: #[repr(C)] on a type that never crosses an FFI or wire boundary. Fix: remove it unless the bytes have to match something outside the process.
Assuming field order in a normal struct. It is not defined, and transmuting or reading raw bytes on that assumption is undefined behavior. Symptom: unsafe code doing pointer arithmetic on field offsets. Fix: offset_of!, or #[repr(C)] if you truly need a stable layout.
Where the C# model wins
Three places, and they are not small.
You do not have to make this decision at all. In C# you write class, the language decides everything downstream, and for a service where the database round trip dominates, that is correct and the mental overhead saved is real. Most of the code most people write does not need per-use-site layout control, and paying attention to it is a cost with no return.
UTF-16 indexing is O(1) and the data model is simpler when your input is ASCII. Parsing a fixed-width protocol, walking a header, scanning for a delimiter, all of these are more direct with s[i] than with char_indices. Rust gives you as_bytes for that, but you have left the string type to get it. .NET also gives you string interning and StringBuilder, and its string immutability makes reasoning about shared state easier than Rust's owned-mutable String does in some designs.
And .NET's Span<T> plus ArrayPool<T> plus stackalloc cover a large part of the same territory Rust's slices cover, with a shorter path from working code to fast code. If you already have a C# service and the layout is your problem, you can usually fix it in C# without leaving C#. That should be said plainly, because the answer to "my .NET service allocates too much" is very often "use structs and pooling", not "rewrite it in Rust".
Checking yourself
Why does Option<Box<T>> fit in eight bytes when Option<i32> needs eight for a four-byte payload?
Box can never be null, so the null bit pattern is a niche the compiler uses for None. i32 uses every bit pattern for a real value, so there is no niche, a discriminant byte gets added, and alignment rounds five up to eight.
A struct has a bool, a u64, and a u8, declared in that order. What is its size, and what would it be with #[repr(C)]?
On the x86_64 compiler measured above, the default layout is sixteen bytes and the #[repr(C)] layout is twenty-four. The default layout is not guaranteed; the C layout follows the target's C ABI, including its alignment rules.
Your function needs to return the first three characters of a user-supplied name. Why is &name[..3] wrong, and what do you write instead?
Byte three may land inside a multi-byte character, and slicing there panics. Use name.char_indices().nth(3) to find the byte offset of the fourth character and slice at that, or take name.chars().take(3).collect::<String>() if you are producing a new owned string.
You are holding two million small records in a Rust Vec and the same two million in a C# List<T> of a class. Where does the memory difference come from, and how would you close it in C# without changing languages?
In the measured x64 example, the class version has object overhead for each record plus references in the array. A value-type array stores records inline and has similar element storage to the Rust Vec in this example. Converting values to object or an interface may box them; check the actual APIs and runtime behavior.
Get the next deep dive by email
New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.
You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.
Written by Zeeshan Adil
I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.