learn deep. ship safe.Practice testsFollow ByteMunSubscribe
ProgrammingTrending #4

Why Rust Uses Less Memory Than Python: Anthropic's API and Our Test

Anthropic's results chart shows more than 80% lower memory after it moved its Messages API from Python to Rust. Here is why Rust uses less memory, shown with a test you can run yourself.

Why Rust uses less memory: a large box of loose Python objects with headers next to a small box of tightly packed Rust values
Python keeps each value as a separate object with a header; Rust packs plain values side by side.

Why Rust uses less memory than Python comes down to three things. Rust stores primitive values such as integers without a per-object header. It cleans up ordinary values at points its ownership rules fix in advance, with no reference count or collector. And its collections keep elements side by side. Anthropic's Messages API move to Rust is a large real-world case, with more than 80% lower memory in its results chart.

This explainer covers what Anthropic changed, how CPython and Rust store the same data, ByteMuni's runnable memory test, and when a Rust rewrite pays off.

Why Rust uses less memory than Python: the short answer

Python and Rust make different promises about data. In Python, every value is a full object that the runtime tracks. In Rust, a primitive such as an i64 is just its bytes, and an ordinary value is cleaned up at a point the compiler works out from ownership rules.

That difference shows up in three places:

  • No per-value header. A Python integer carries a reference count and a type pointer next to its value. A Rust i64 is 8 bytes and nothing else.

  • Cleanup points are fixed at compile time. CPython primarily manages object lifetimes through reference counting, plus a collector for reference cycles. Ordinary Rust values need neither; cleanup runs where the owner goes out of scope. Allocation and freeing still happen at runtime.

  • Compact layout. A Python list stores pointers to objects spread across the heap. A Rust Vec<T> stores its elements contiguously in one heap allocation.

None of this makes Python wrong. Those headers and counters buy flexibility: any variable can hold any type, and objects can be inspected at runtime.

What Anthropic changed when it moved its Messages API to Rust

On November 25, 2026, Anthropic published an engineering post on migrating its Messages API from Python to Rust. The Messages API is the service developers call to send prompts to Claude models and get responses back.

According to the post, API traffic grew roughly 1,800 times between early 2024 and fall 2026. At that scale, the cost of every request matters.

The results Anthropic reports

MetricChange after the Rust migrationMeasurement note
CPU per requestAbout 70% lessBody text and chart; caption says CPU is from one region
Memory usageMore than 80% lowerChart reports per-request memory; caption specifies all-production coverage
Median time to first tokenAbout 20% lowerBody text and chart; customers' Claude Code requests over a shorter period

The memory figure deserves care. It appears only in the chart, not in the body text. The chart reports memory per request, while its caption says memory covers all of production, and the post does not spell out how those two descriptions fit together. So the reporting scope is not fully clear. The post also does not explain why memory fell; the explanation below is ByteMuni's, built from the Python and Rust documentation.

The post does describe the kind of overhead the team was fighting. It says Python added cost each time it created an object, freed memory, or passed work on to the next task.

Why the first, partial rewrite was not enough

Anthropic did not start with a full rewrite. In March 2026, the team rewrote only the code that parses model output in Rust and called it from Python. That cut the API's CPU use by about 8% to 10%, the post says.

The team dropped that approach. Each token crossed the Python–Rust boundary three times, and the gains did not justify the extra complexity. That lesson returns in the decision guide below.

How Claude wrote the code, and why checking it was the hard part

According to Anthropic, Claude wrote a first version of the API's core request path in about a week. ByteMuni's guide on how coding agents work explains the write-run-fix loop behind that.

Proving the new code behaved like the old code took far longer. The post says the Rust version passed about 98% of its tests in April, yet only about a quarter of inputs matched on production traffic. Anthropic ran it in shadow mode, beside the Python service, and tracked the input match rate from 24% in late April to 99.6% by August. In the post's words, "Verification, not generation, had become the bottleneck."

That shadow-testing setup is a verification loop at production scale. ByteMuni has covered the same idea for agent systems in engineering reliable AI agents.

How does Python store a number in memory?

To see where the memory goes, start with one integer in CPython, the standard Python interpreter.

Every value is an object with a header

Python's data model states that every object has an identity, a type and a value. In CPython, the identity is the object's memory address. So even the number 1,000,000 is a separate object somewhere on the heap.

Each object starts with a common header. The CPython C API documentation says that in a normal release build this header holds the object's reference count and a pointer to its type object. On a 64-bit machine, those are 8 bytes each. Integers also carry a size field, because Python integers can grow to any length.

The result: sys.getsizeof(1_000_000) returns 28 bytes on ByteMuni's test machine, for a value that fits in 8. A float takes 24 bytes.

A list holds pointers, not numbers

A Python list does not contain the numbers. It contains an array of 8-byte pointers, and each pointer leads to a separate integer object. One million integers therefore cost about 8 MB for the pointers plus 28 MB for the objects. ByteMuni measured 36.0 MB on Python 3.10, or 36 bytes per number (40 on Python 3.12 and 3.13, explained in the test section).

Diagram of why Rust uses less memory: a Python list of pointers to separate int objects vs a Rust Vec of packed 8-byte numbers
A Python list stores 8-byte pointers to separate 28-byte int objects; a Rust Vec stores the 8-byte numbers directly (sizes from ByteMuni's Python 3.10 test).

Each instance carries a dictionary

A plain class instance stores its attributes in a per-instance dictionary, __dict__. On Python 3.10, ByteMuni measured a three-field User instance at 48 bytes and its dictionary at 104 bytes, before counting the three value objects.

The __slots__ feature removes that dictionary. The documentation says slots deny the creation of __dict__ and __weakref__, and that the space saved can be significant. The values are still separate objects, though, so slots shrink the cost without removing it.

Reference counts and the cycle collector

CPython primarily manages object lifetimes through reference counting. The data model describes a reference-counting scheme with optional delayed detection of cyclic garbage, and it labels this a CPython implementation detail. Every time a new reference to an object is made or dropped, the count changes; at zero, the object is freed.

Reference counting cannot free objects that point to each other in a cycle. For those, the gc module runs a collector that, in the docs' words, supplements the reference counting. It sorts objects into three generations and starts a collection when allocations minus deallocations pass a threshold.

How Rust lays out the same data

Rust takes a different route. The Rust Book's chapter on ownership describes it as a third approach, between garbage collection and manual freeing: memory is managed through ownership rules that the compiler checks.

Ownership frees memory at a known point

The rules are short. Each value has one owner. There can only be one owner at a time. When the owner goes out of scope, the value is dropped.

Because the compiler knows where each owner's scope ends, it inserts the cleanup there. The Book says Rust calls a function named drop automatically at the closing curly bracket. This gives deterministic cleanup without a tracing garbage collector: ordinary owned values store no reference count, and nothing scans the heap, so there are no collection pauses for them.

Two caveats keep this accurate. For shared ownership, Rust offers Rc<T>, which counts references at runtime, and Arc<T>, its thread-safe version. And heap allocation and freeing are still runtime calls to an allocator; ownership decides when they happen, not whether they cost anything.

Stack, heap, and packed values

The Book explains that fixed-size data can live on the stack, while data whose size is unknown or can change goes on the heap. A Vec<i64> is a small descriptor (pointer, length and capacity) that points to one heap block of plain 8-byte values, with no header on each. String and Box<T> also keep their data on the heap behind a pointer.

Structs work the same way. The Rust Reference on type layout lists u64 and f64 at 8 bytes and u32 at 4. It also says a type's size is always a multiple of its alignment. So a struct of u64, u32 and f64 has 20 bytes of data and is padded to 24. The default layout may reorder fields, so 24 is what this compiler produced, as the test below confirms.

Rust vs Python memory: ByteMuni's test

ByteMuni ran a small memory test on November 26, 2026, on an x86_64 Linux machine (Intel Xeon at 2.30 GHz). Python ran on 3.10.20, 3.12.13 and 3.13.18. The newest 3.12 release, 3.12.16, ships as source code only and could not be built in the test environment, so 3.12.13 is the newest 3.12 build tested. Ubuntu's older system Python 3.12.3 gave identical figures. Rust was compiled with rustc 1.97.0 in release mode (-O). Each script ran five times per version and gave identical output.

Treat this as an illustration of data layout, not a definitive Python-versus-Rust benchmark. The two languages use different allocators and allocation strategies, and the test counts requested bytes, not memory the operating system reports.

How the test measures memory

The Python script uses tracemalloc, the standard library's tool for tracing memory blocks allocated by Python. It records traced memory before and after building each data set, while keeping the data alive. The Rust script wraps the system allocator in a small counter that adds requested bytes on every allocation, subtracts them on every free, and adjusts them on every resize (realloc), so growing a vector is counted too. Both scripts use only the standard library; NumPy is an optional extra row.

Each User has an integer ID, an integer age and a float score, all unique per user, to mirror the Rust struct. Small integers are avoided, because CPython reuses cached objects for them.

The Python script

"""ByteMuni memory test: how much memory Python uses for plain data.

Run:  python3 mem_python.py
Uses the standard library (sys, tracemalloc, platform, array).
NumPy is optional; its row is skipped if NumPy is not installed.
"""
import array
import platform
import sys
import tracemalloc

N_INTS = 1_000_000
N_USERS = 100_000

class User:
    def __init__(self, user_id, age, score):
        self.user_id = user_id
        self.age = age
        self.score = score

class SlotUser:
    __slots__ = ("user_id", "age", "score")

    def __init__(self, user_id, age, score):
        self.user_id = user_id
        self.age = age
        self.score = score

def measure(build):
    """Return bytes still allocated after build() runs (object is kept alive)."""
    tracemalloc.start()
    before = tracemalloc.get_traced_memory()[0]
    data = build()
    after = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return after - before, data

def make_users(cls):
    # Each user gets its own int id, int age and float score,
    # mirroring the Rust struct (u64, u32, f64).
    return [cls(10_000 + i, 1_000 + i, i * 0.5) for i in range(N_USERS)]

def main():
    print(f"Python {platform.python_version()} on {platform.machine()}")

    # Bytes requested per int object, as tracemalloc sees it. This can
    # differ from sys.getsizeof, and by how the int was created.
    tracemalloc.start()
    before = tracemalloc.get_traced_memory()[0]
    one = int("1000000")  # parsed from text at runtime: a fresh object
    print(f"traced bytes, int from text  = {tracemalloc.get_traced_memory()[0] - before}")
    tracemalloc.stop()
    del one
    used, nums = measure(lambda: list(range(10_000, 10_000 + N_INTS)))
    per_int = (used - sys.getsizeof(nums)) / N_INTS
    print(f"traced bytes, int from range = {per_int:.0f} (average, list itself excluded)")
    del nums

    print(f"sys.getsizeof(1_000_000)    = {sys.getsizeof(1_000_000)} bytes (one int object)")
    print(f"sys.getsizeof(3.14)         = {sys.getsizeof(3.14)} bytes (one float object)")

    used, _ = measure(lambda: list(range(10_000, 10_000 + N_INTS)))
    print(f"{N_INTS:,} ints in a list   = {used / 1e6:.1f} MB "
          f"({used / N_INTS:.1f} bytes per number)")

    used, _ = measure(lambda: array.array("q", range(10_000, 10_000 + N_INTS)))
    print(f"{N_INTS:,} ints in array('q') = {used / 1e6:.1f} MB "
          f"({used / N_INTS:.1f} bytes per number)")

    try:
        import numpy as np  # optional: pip install numpy
        used, _ = measure(lambda: np.arange(10_000, 10_000 + N_INTS, dtype=np.int64))
        print(f"{N_INTS:,} ints in NumPy int64 = {used / 1e6:.1f} MB "
              f"({used / N_INTS:.1f} bytes per number, NumPy {np.__version__})")
    except ImportError:
        print("NumPy not installed: skipping the NumPy row")

    used, _ = measure(lambda: make_users(User))
    print(f"{N_USERS:,} User objects    = {used / 1e6:.1f} MB "
          f"({used / N_USERS:.0f} bytes each)")

    used, _ = measure(lambda: make_users(SlotUser))
    print(f"{N_USERS:,} __slots__ Users = {used / 1e6:.1f} MB "
          f"({used / N_USERS:.0f} bytes each)")

if __name__ == "__main__":
    main()

Run it with python3 mem_python.py. For the NumPy row, run pip install numpy first; without NumPy, the script skips that row.

The Rust script

// ByteMuni memory test: how much memory Rust uses for the same data.
//
// Run:  rustc -O mem_rust.rs && ./mem_rust
// Uses only the standard library. A small counting allocator records
// how many heap bytes are live (requested sizes, not resident memory),
// so the numbers are measured, not calculated from type sizes.

use std::alloc::{GlobalAlloc, Layout, System};
use std::mem::size_of;
use std::sync::atomic::{AtomicUsize, Ordering};

struct Counting;
static LIVE: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let ptr = unsafe { System.alloc(layout) };
        if !ptr.is_null() {
            // Count only allocations that succeeded.
            LIVE.fetch_add(layout.size(), Ordering::Relaxed);
        }
        ptr
    }
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        LIVE.fetch_sub(layout.size(), Ordering::Relaxed);
        unsafe { System.dealloc(ptr, layout) }
    }
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        // Count growth and shrinking explicitly, so no allocation path is missed.
        let new_ptr = unsafe { System.realloc(ptr, layout, new_size) };
        if !new_ptr.is_null() {
            LIVE.fetch_add(new_size, Ordering::Relaxed);
            LIVE.fetch_sub(layout.size(), Ordering::Relaxed);
        }
        new_ptr
    }
}

#[global_allocator]
static GLOBAL: Counting = Counting;

#[allow(dead_code)]
struct User {
    user_id: u64,
    age: u32,
    score: f64,
}

const N_INTS: usize = 1_000_000;
const N_USERS: usize = 100_000;

fn main() {
    println!("size_of::<i64>()  = {} bytes", size_of::<i64>());
    println!("size_of::<f64>()  = {} bytes", size_of::<f64>());
    println!("size_of::<User>() = {} bytes (u64 + u32 + f64, with padding)", size_of::<User>());

    let before = LIVE.load(Ordering::Relaxed);
    let numbers: Vec<i64> = (10_000..10_000 + N_INTS as i64).collect();
    let used = LIVE.load(Ordering::Relaxed) - before;
    println!(
        "{} i64 in a Vec    = {:.1} MB ({:.1} bytes per number)",
        numbers.len(),
        used as f64 / 1e6,
        used as f64 / N_INTS as f64
    );

    let before = LIVE.load(Ordering::Relaxed);
    let users: Vec<User> = (0..N_USERS)
        .map(|i| User {
            user_id: 10_000 + i as u64,
            age: 1_000 + i as u32,
            score: i as f64 * 0.5,
        })
        .collect();
    let used = LIVE.load(Ordering::Relaxed) - before;
    println!(
        "{} User structs    = {:.1} MB ({:.0} bytes each)",
        users.len(),
        used as f64 / 1e6,
        used as f64 / N_USERS as f64
    );
} // `numbers` and `users` are dropped here: their memory is freed at this brace.

Run it with rustc --edition 2024 -O mem_rust.rs && ./mem_rust. The unsafe blocks are only needed for the counting allocator; the measured code itself is ordinary safe Rust.

The results

DataPython 3.10.20Python 3.12.13Python 3.13.18Rust 1.97.0
One integer28 bytes28 bytes28 bytes8 bytes (i64)
One float24 bytes24 bytes24 bytes8 bytes (f64)
1,000,000 integers in a list / Vec36.0 MB (36 bytes each)40.0 MB (40 bytes each)40.0 MB (40 bytes each)8.0 MB (8 bytes each)
1,000,000 integers in array('q')8.2 MB8.2 MB8.2 MBnot applicable
1,000,000 integers in a NumPy int64 array8.0 MB (NumPy 2.2.6)8.0 MB (NumPy 2.5.5)8.0 MB (NumPy 2.5.3)not applicable
100,000 User objects24.0 MB (240 bytes each)18.4 MB (184 bytes each)19.2 MB (192 bytes each)2.4 MB (24 bytes each)
100,000 User objects with __slots__14.4 MB (144 bytes each)15.2 MB (152 bytes each)15.2 MB (152 bytes each)not applicable

One integer and one float are from sys.getsizeof and size_of; the other rows are measured allocations. Here is the raw output for Python 3.13 and Rust; the full output for all versions is in the download.

$ python3.13.18 mem_python.py
Python 3.13.18 on x86_64
traced bytes, int from text  = 28
traced bytes, int from range = 32 (average, list itself excluded)
sys.getsizeof(1_000_000)    = 28 bytes (one int object)
sys.getsizeof(3.14)         = 24 bytes (one float object)
1,000,000 ints in a list   = 40.0 MB (40.0 bytes per number)
1,000,000 ints in array('q') = 8.2 MB (8.2 bytes per number)
1,000,000 ints in NumPy int64 = 8.0 MB (8.0 bytes per number, NumPy 2.5.3)
100,000 User objects    = 19.2 MB (192 bytes each)
100,000 __slots__ Users = 15.2 MB (152 bytes each)

$ rustc --edition 2024 -O mem_rust.rs && ./mem_rust   (rustc 1.97.0 (2d8144b78 2026-07-07))
size_of::<i64>()  = 8 bytes
size_of::<f64>()  = 8 bytes
size_of::<User>() = 24 bytes (u64 + u32 + f64, with padding)
1000000 i64 in a Vec    = 8.0 MB (8.0 bytes per number)
100000 User structs    = 2.4 MB (24 bytes each)
Bar chart of the Rust vs Python memory test: 100,000 User objects use 24.0 MB in Python 3.10, 14.4 MB with slots, 2.4 MB in Rust
Memory for 100,000 three-field User objects, measured by ByteMuni on November 26, 2026 (Python with tracemalloc, Rust with a counting allocator). Source: ByteMuni test.

What the numbers show

On Python 3.10, the 240 bytes per User add up from parts measured separately, by ByteMuni's count: a 48-byte instance, a 104-byte dictionary, two 28-byte integers, a 24-byte float and an 8-byte list pointer. With __slots__, the dictionary goes away and the instance itself is 56 bytes, giving 144 bytes. Rust stores the same three fields in 24 bytes, one-tenth of the plain class.

Python 3.12 and 3.13 used less memory than 3.10 for plain class instances but more for the integer list: 40 bytes per number instead of 36. The script breaks that down. On 3.12 and 3.13, each integer created by range requested 32 bytes from Python's allocator, while an integer parsed from text requested 28. sys.getsizeof reports 28 for both, because it reports the object's size, not the allocation request. Add the 8-byte list pointer and you get 40. On 3.10, both kinds of integer requested 28 bytes. These are traced allocation sizes observed in this environment, not a guaranteed object-size difference across CPython builds. ByteMuni did not trace the source-level reason for the 32-byte request.

In this test, each Python integer-list element took about 4.5 to 5 times the memory of a Rust i64 element on every version.

When NumPy and array get close to Rust

The gap comes from storing each number as a separate object, not from Python itself. The standard array module and NumPy arrays store raw values in one block. In ByteMuni's test, one million integers took 8.2 MB in array('q') and 8.0 MB in a NumPy int64 array, close to Rust's 8.0 MB.

This works for large runs of same-type numbers processed with whole-array operations. It helps far less for mixed-field records like User, or for Python loops over single items, because each item read back becomes a Python object again.

The limits of this test

  • It shows a principle, not Anthropic's result. It does not reproduce or explain Anthropic's 80% figure, which comes from a full production service.

  • Requested bytes, not process memory. tracemalloc traces blocks from Python's allocators, and the Rust counter records requested sizes. Neither equals the resident set size (RSS) the operating system reports.

  • Different allocators. CPython serves small objects from its own allocator; the Rust test used the system allocator.

  • Python 3.10 is end-of-life. Python.org says the 3.10 series reached end of life on October 1, 2026, which is why 3.12 and 3.13 are included.

  • One machine. Other CPUs, operating systems or allocator settings can give different figures.

Should you rewrite your Python app in Rust?

Usually not as a first step. Anthropic's post shows a rewrite takes months of verification, even when an AI model writes the first version.

Memory is not the only reason teams move to Rust

Anthropic's biggest reported gain was CPU per request, alongside lower median time to first token. Memory and CPU are linked, because allocating, counting and freeing objects all take CPU time. Anthropic did not publish cost savings, so ByteMuni will not estimate them.

Other moves had other reasons. Discord's 2020 post on leaving Go for Rust traces latency spikes about every two minutes to Go's garbage collector scanning a large cache. Bun, a JavaScript runtime, moved from Zig to Rust in July 2026; its post reports 609 MB instead of 6,745 MB over 2,000 builds, much of it from fixing a leak of about 3 MB per build.

When a rewrite pays off, and when it doesn't

SituationRust rewrite likely worth it?Why
Hot request path in a service at very large scaleOften yesPer-request savings multiply across traffic, as in Anthropic's case
Long-running service with tight memory limits (small VPS, Kubernetes pods with low limits)Often yesLower memory per request means more requests per instance
Latency-sensitive service hurt by pausesSometimesProfile first; Discord's problem was a collector, not Python
Scripts, automation, small Django or Flask appsRarelyDevelopment speed matters more than bytes
ML research and notebook codeRarelyHeavy work already runs in native libraries like NumPy and PyTorch
Team with no Rust experience and no time to learnNoVerification and maintenance cost will dominate

Cheaper steps to try first

  1. Measure. Use tracemalloc snapshots to find which lines allocate the most, and check RSS in your container or VPS dashboard.

  2. Add __slots__ to classes with many instances. In ByteMuni's test this cut per-object memory by 40% on Python 3.10. Trade-off: you can no longer add arbitrary attributes to instances.

  3. Store numbers in arrays, not lists. In ByteMuni's test, array('q') and NumPy cut one million integers from 36–40 MB to about 8 MB. Trade-off: reading items one by one in a Python loop turns them back into objects.

  4. Move one hot, self-contained function to Rust with PyO3, a library of Rust bindings for building Python extension modules. Its guide recommends maturin: pip install maturin, then maturin init (choose pyo3), then maturin develop.

Step 4 carries Anthropic's warning. Its partial rewrite gained only 8% to 10% CPU because data crossed the language boundary for every token. Hand Rust a large batch once, not millions of small calls.

How students should start learning Rust

For Indian CS students and Python developers, Rust is worth learning for the mental model alone: who owns data, and when it is freed. That helps in interviews on memory, pointers or system design. For where to spend study time overall, see ByteMuni's piece on what students should learn in DSA vs AI.

A four-week starter path, using the free official Rust Book:

  1. Week 1: setup and basics. Install with rustup, use cargo new and cargo run, and learn variables, types and functions.

  2. Week 2: ownership and borrowing. Read the ownership chapter twice. Practice moving a String into a function, then passing &String and &mut String instead.

  3. Week 3: Vec, String, structs and enums. Rewrite a small Python script, such as a CSV word counter, in Rust.

  4. Week 4: errors with Result. Replace each unwrap() in your week-3 program with ?. Then run this article's memory test and change the struct fields to see the size change.

ByteMuni's Rust programming language guide with examples is a good companion for weeks 1 to 3.

My take on the Rust migration trend

My read is that the most useful part of Anthropic's post is not the 70% or the 80%. It is the gap between "passes 98% of tests" and "matches 24% of production inputs". Code generation has become cheap, and checking that new code behaves like old code has not. Teams planning any rewrite, to Rust or anything else, should build the shadow-traffic comparison before writing the new version. I would also treat the failed partial rewrite as a design rule: decide where the language boundary sits by how often data crosses it, not by which function looks slowest.

The bottom line on why Rust uses less memory

Rust uses less memory than ordinary Python object collections because primitive values carry no per-object header, collections store elements contiguously, and ownership gives deterministic cleanup. Rust is not the only route to compact data, though. Python's array module and NumPy store numbers just as compactly, as the test showed. Measure first, fix the data structures, and consider Rust when scale, memory limits and performance needs justify the extra engineering. For a script or a small app, stay in Python.

Frequently asked questions

Does Rust have a garbage collector?

No. The Rust Book describes ownership as an alternative to garbage collection: Rust calls drop when a value's owner goes out of scope. For data with several owners, Rc<T> and Arc<T> add runtime reference counting, but there is still no tracing collector.

How much memory does a Python integer use?

On 64-bit CPython, sys.getsizeof reports 28 bytes for an integer like 1,000,000, against 8 bytes for a Rust i64. In a list, each integer also needs an 8-byte pointer: ByteMuni measured 36 bytes per number on Python 3.10 and 40 on 3.12 and 3.13, where integers created by range requested 32 bytes each.

Does __slots__ make Python use as little memory as Rust?

No. __slots__ removes the per-instance __dict__, which cut memory by 40% in ByteMuni's Python 3.10 test (240 to 144 bytes per object). Each field is still a separate Python object, so Rust's 24-byte struct remained six times smaller.

Did Anthropic explain why its Rust API uses less memory?

No. The "more than 80%" figure appears only in a results chart, whose caption says memory covers all of production while CPU comes from one region. The post does not explain the cause; ByteMuni's explanation comes from the Python and Rust documentation and its own test.

Can I use Rust from Python without a full rewrite?

Yes. PyO3 provides Rust bindings for building Python extension modules, and its guide recommends the maturin build tool. Anthropic's experience shows the gain can be small if data crosses the Python–Rust boundary very often.

Can NumPy match Rust's memory use?

For large arrays of same-type numbers, nearly. In ByteMuni's test, one million integers took 8.0 MB in a NumPy int64 array and 8.2 MB in the standard array('q'), against 8.0 MB in a Rust Vec<i64>. The gain shrinks for mixed-field records and for Python loops that read items one at a time.

Concepts in this article

Memory management
How a runtime allocates and frees memory, garbage collection, and how leaks happen.
Rust
A systems programming language with memory safety enforced at compile time.
Artificial intelligence
Computer systems that perform tasks that normally need human intelligence.
Claude
Anthropic's family of AI models and assistants.
Numbers
Floating-point numbers, BigInt, NaN and precision pitfalls.
Objects
Collections of key–value properties, the building block of most JavaScript data.
Python
A general-purpose language widely used for scripting, web back ends and machine learning.
Variables and scope
Where a variable can be read: global, function and block scope, and how let, const and var differ.

How we research, write and check articles

Written by

· Senior Software Engineer

Deepak Kumar is a Senior Software Engineer based in New Delhi. He reaches for Python where the job calls for it: the ingestion pipeline behind his trend-intelligence product TrendMeToday is Python and FastAPI. He started ByteMuni to publish clear, source-checked guides for working developers.