A programming language is a set of decisions about what the machine should do for you and what you must do yourself, and each of these four moved one kind of mistake to a different moment: Python finds it while the program runs and tells you clearly; C++ trusts you and may give no signal at all (undefined behaviour); Rust refuses to compile until it can prove a whole class of mistakes absent; TypeScript checks while you edit, then removes every check before the code runs.
Fig. 1, step by step: the same program in four lanes, source at the back, the machine at the front
tokens.py, tokens.cpp, tokens.rs and tokens.ts. The rows across the lanes are the moments a mistake can meet: while you edit, when it compiles, when it runs, and no signal at all. Each language's own map is Fig. 1 on its page: Python, C++, Rust, JavaScript and TypeScript.JSON.parse pass in TypeScript, and undefined + 1 is NaN). Sections 3, 6 and 10.-O0 got 1,014,609, a data race and so undefined behaviour; Rust refused the program (E0499), and its Arc<Mutex> version got 4,000,000; JavaScript's four async tasks share one thread and its event loop, and got 4,000,000 (measured, section 9).Each section below is one axis of this map, shown on the same small program in all four languages. Most of what feels strange in a new language is that language catching, at its moment, a mistake Python would have caught at a different one.
You need: everyday Python; every other term is defined where it first appears. Python is the reference column everywhere: each axis shows what Python does, then what the others make you do instead, and why.
| Python | C++ | Rust | TypeScript | |
|---|---|---|---|---|
| Founding value | Readability: "Readability counts" | Zero overhead, and compatibility with C | Memory and thread safety checked before the program runs, with no garbage collector | JavaScript plus types that disappear; never break existing JavaScript |
| In ML work today | The glue and the research language | The substrate: PyTorch's core, CUDA kernels, llama.cpp | The new substrate of Python's tools (uv, ruff, tokenizers, polars) and fast services | LLM apps, agents, MCP servers, coding harnesses |
| How code runs | Compiled to bytecode, interpreted; hot code specialised | Compiled ahead of time to machine code | Compiled ahead of time to machine code (LLVM) | Types erased, then V8 interprets and JIT-compiles the JavaScript |
| Types | Dynamic; optional hints checked by separate tools | Static, by name | Static, by name, strongly inferred | Static, by shape, gradual, unsound on purpose |
| b = a means | Share the object | Copy it | Move it (a is now unusable) | Share the object |
| Memory freed by | Reference counting plus a cycle collector | You, through destructors (RAII) | The owner going out of scope, checked by the compiler | A tracing garbage collector |
| Errors, nothing | Exceptions; None | Exceptions or std::expected; nullptr | Result and Option values; panic for bugs | Exceptions; null and undefined |
| Integers, strings | Unbounded ints; code points | Fixed ints, signed overflow is undefined behaviour; bytes | Fixed ints, overflow panics in debug; UTF-8, no indexing | 64-bit floats plus BigInt; UTF-16 units |
| Abstraction | Duck typing, Protocols | Templates and concepts; virtual functions | Traits; generics or dyn | Structural interfaces, generics |
| Threads | GIL by default; free-threaded build supported since 3.14 | Free; data races are undefined behaviour | Free; data races refused at compile time | One thread and an event loop; workers for more |
| Waiting for I/O | asyncio: one event loop | Threads, or a library (Asio) | async with a runtime you add (tokio), on several threads | Built in: the event loop and promises |
| When you get it wrong | An exception | Undefined behaviour: anything can happen | A compile error, or a panic | A runtime exception, or a silent NaN |
| Releases | Yearly | ISO standard every three years | Every six weeks; editions | JavaScript yearly; TypeScript several times a year |
| Toolchain | uv for interpreters, environments and locks; ruff; a type checker | A compiler, CMake, sanitizers; no standard package manager | cargo does everything; clippy, rustfmt | A runtime (Node, Bun, Deno), npm or pnpm, and tsc to check |
| Our program, 200,000 lines | (Node) |
Last row: median wall time from the Benchmark tab (measured, , Apple M1 Pro); read section 12 before quoting it.
One running program. All four languages solve the same small job: read a chat log in JSON Lines (one JSON object per line), count word-like tokens in each message, add them up per user, and print the five heaviest users; malformed lines are counted and skipped. The Rosetta tab has the four complete programs side by side, the Benchmark tab times them, the Design space tab gives every axis by every language with a runnable snippet per cell and the full collection of false friends, and the Toolchain atlas lists the tools of each ecosystem. The four language pages and their children are at the end of this tab.
Every code snippet on this page was run for it, and every output and compiler message is the real text (toolchains: ). C++ examples were compiled with Apple clang 17 from the Command Line Tools (the macOS 26 SDK, which has C++23's <expected>); sanitizer runs used LLVM clang 23.1.2, because Apple's sanitizer runtimes do not start on macOS 27. The Benchmark and Rosetta tabs used this Mac's older Apple clang 14. Numbers marked measured were measured for this page on one laptop; illustrative marks a picture that shows a shape rather than data.
Research on experienced programmers learning a second language found that they learn by mapping onto what they already know, and that most of their trouble comes from the places where the mapping silently breaks: in 450 Stack Overflow questions across 18 languages the authors found 276 instances of interference from a faulty assumption carried over from another language, and interviews showed programmers "make failed attempts to relate a new programming language with what they already know" (Shrestha, Botta, Barik and Parnin, ICSE 2020). So each section keeps a closed false friends box: things that look like Python and are not.
A founding value is the goal a language's designers would not give up when two goals conflicted. Each of the four wrote theirs down, and every later section is one of them playing out.
"Readability counts." "Explicit is better than implicit." "Errors should never pass silently." "There should be one-- and preferably only one --obvious way to do it."
From PEP 20, The Zen of Python. The programmer's time matters more than the machine's: no declarations, no compile step, and a clear exception at the line that made the mistake.
Costs: every value carries type information and a reference count, and every operation is looked up while the program runs, so a plain Python loop is tens of times slower than compiled code (section 12).
"You don't pay for what you don't use. What you do use is just as efficient as what you could reasonably write by hand."
The zero-overhead principle (after Stroustrup), plus compatibility with C: "C with Classes" in 1979, Cfront 1.0 in 1985 (cppreference history). Nothing is checked unless you ask, so abstractions compile to what hand-written C would.
Costs: the language trusts you. Reading freed memory, overflowing a signed integer or racing two threads is undefined behaviour: no error, and no guarantee about what happens (section 10).
"with no runtime or garbage collector" ... "Rust's rich type system and ownership model guarantee memory-safety and thread-safety, enabling you to eliminate many classes of bugs at compile-time."
From rust-lang.org ("Performance" and "Reliability"; Rust 1.0 was announced 15 May 2015). C++'s speed without C++'s undefined behaviour, by making the compiler prove who owns each value and who may change it.
Costs: the compiler rejects programs that are correct but that it cannot prove correct, so the first weeks are spent learning its rules; compile times are long.
"Use a consistent, fully erasable, structural type system." Non-goal: "Apply a sound or 'provably correct' type system. Instead, strike a balance between correctness and productivity."
From TypeScript's Design Goals. TypeScript (0.8 in October 2012) is JavaScript plus types that are checked and then deleted. JavaScript, standardised as ECMAScript in June 1997 (ECMA-262, Introduction), has an older rule: "'don't break the Web' is the number one design principle" (Mathias Bynens, V8 team, 2018), so its old mistakes can never be removed, only avoided.
Costs: types can be wrong at run time (nothing checks data arriving from the network), and JavaScript's quirks (one number type, two kinds of "nothing") stay forever.
Two of these are about the programmer (Python's readability, TypeScript's productivity) and two about the machine (C++'s zero overhead, Rust's zero overhead plus proof). That split predicts most of this page: Python and TypeScript share objects freely and clean up with a garbage collector; C++ and Rust lay values out exactly as written and free them at a known moment.
Python is the glue and the research language; C++ is the substrate under it (PyTorch's core, CUDA kernels, llama.cpp); Rust is the new substrate of Python's own tools, so you already run it every day; TypeScript is the language of LLM applications and agents. The chart counts the source of well-known repositories by language, as GitHub's own classifier (linguist) reports it, fetched through GitHub's API on .
Share of bytes of source per language (tests and examples included, generated files mostly excluded by linguist). Bytes are not importance: PyTorch's C++ is a quarter of its bytes but carries most of its speed. The astral-sh/ty repository holds only packaging and Python tests: its README says development "takes place in the Ruff repository", so ty's Rust lives inside astral-sh/ruff.
ggml has a C core (ggml.c, the CPU kernels in ggml-cpu.c and quants.c, about 81,000 lines of C) surrounded by C++ (about 221,000 lines: the backend interface ggml-backend.cpp, the GGUF file reader gguf.cpp, the CPU operators in ggml-cpu/ops.cpp and the GPU backends), and the model loading, tokenizer, sampling and server are C++ (src/ 91,000 lines, tools/ 57,000), with 47,000 lines of CUDA for NVIDIA GPUs (commit , counted by read/code/llama/excerpts.sh). C is used where the code must be callable from any language and compile anywhere; C++ where the code needs containers, RAII and templates.A processor only executes machine code. Each language is a different route from your text to it, and the route decides when the translation happens and how much it knows then. Translation time is also checking time: what is checked while translating is caught on every path, including the ones your tests never run (the hero above).
tsc checks the types and writes JavaScript with every annotation removed; Node 22.18 and later can also run a .ts file directly by blanking the annotations out (Node docs). Types never exist at run time.Predict how many instructions each route spends on one character, then step one line of the token loop, if tok and not inside: n += 1, through each. All real output: Python's dis, clang's and rustc's assembly (AArch64: cmp, b.ne, ldrb), V8's bytecode and node --print-opt-code, and tsc's output.
What the counts mean. For each character CPython executes 29 bytecode instructions, each of them dozens of machine instructions inside the interpreter (fetch, jump to the handler, check types, update reference counts). The compilers turned the same loop into 16 (clang) or 17 (rustc) machine instructions per byte, then rewrote it to process 8 (clang) or 32 (rustc) bytes at once with SIMD instructions. V8 got close to the compilers' simple version after watching the function run. That is most of the speed gap of section 12, before any library or algorithm is involved.
Translation time is also checking time: whatever a language checks while translating is caught on every path, including the ones your tests never execute.
| Caught by | Python | C++ | Rust | TypeScript |
|---|---|---|---|---|
| Translation | Syntax errors only | Types, missing functions, template constraints | Types, ownership, borrowing, data races, unhandled cases | Types (then erased) |
| A separate checker | mypy, pyright, ty: types, if you annotate | clang-tidy, sanitizers (at run time, in tests) | clippy: style and likely bugs | tsc is the checker |
| Run time | Everything else, as exceptions | Little: most mistakes are undefined behaviour, not errors | Index out of bounds, overflow in debug builds, failed unwrap: a panic | JavaScript's own errors; wrong types pass silently |
Ahead-of-time compilation costs build time (the Benchmark tab measures it: seconds for the Rust program against nothing for Python) and a separate binary for every processor and operating system you ship to. Interpretation costs speed. A JIT costs memory and warm-up time: the first calls are slow, and V8 compiled our function only after it was "hot and stable". TypeScript's erasure costs nothing at run time and checks nothing at run time.
.pyc files in __pycache__); only the bytecode is interpreted.PYTHON_JIT=1 (What's new in 3.14); the 3.14 run above shows JUMP_BACKWARD_NO_JIT.-O2); in Rust, integer overflow panics in a debug build and wraps in a release build (section 7).A type says what kind of value something is and therefore what you may do with it. Every language checks types; the question is when. A dynamically typed language checks each operation as it runs, on the actual values. A statically typed language checks the whole program before it runs. Gradual typing sits between: you annotate where you want and a separate checker reads the annotations, as with Python's hints and TypeScript.
The same mistake in all four: the token counter called with a user id (an integer) instead of the message text. Predict which languages produce a program at all, then pick each one.
Two more distinctions. By name or by shape: in C++ and Rust a value fits a type only if it was declared as that type (nominal typing); in TypeScript any object with the right fields fits (structural typing), like Python's duck typing but checked before running (section 8). Sound or not: a sound type system never lets a value of the wrong type through. Rust's safe subset aims for soundness; TypeScript says plainly that it does not (section 1): any, type assertions (x as Foo) and data from JSON.parse pass unchecked. Python's checkers are similar: an unannotated function is not checked at all.
runs, then failsPython starts running and prints the first result; the error arrives only when the bad call executes, as a TypeError deep inside the function. A type checker (mypy or Astral's ty, each one command) reads the hint text: str and reports the same line without running anything, but only if you run it: Python itself ignores hints.
refused at compile timeThe compiler refuses: there is no conversion from int to std::string_view. No program is produced, so nothing runs.
refused at compile timeError E0308, "mismatched types", with an arrow under the 42. Rust error messages point at the exact place and often suggest a fix; run rustc --explain E0308 for a page about the error.
refused by tsc, runs anywaytsc reports the wrong type (error TS2345). But types are erased, so the same file still runs: Node strips the annotations and executes it, and the function quietly returns 0 because (42).length does not exist and the loop never starts. TypeScript only protects you if tsc is part of your build.
Static types cost writing them (less than you expect: Rust and TypeScript infer most local types) and a compile step. Dynamic types cost finding the mistake later, in tests or in production, and cost speed: an interpreter that does not know n is an integer must check before every addition (section 2). Gradual types cost discipline: the checker sees only what you annotate.
Message type on JSON.parse(line) is a promise you made, not a check. Validate data at the boundary (Pydantic in Python; zod or a hand-written guard like the Rosetta program's isMessage in TypeScript).auto in C++ or let in Rust means dynamic." Both mean "infer the type now"; the type is still fixed at compile time and cannot change later.u64 is like Python's int." It is a fixed 64-bit unsigned integer; section 7 shows what happens at its limit.In Python a variable is a name attached to an object; b = a attaches a second name to the same object, so a change through either is visible through both. Two names for one object are aliases. JavaScript works the same way for objects and arrays. In C++ and Rust a variable is the value, a region of memory of a known size, so b = a must decide what happens to that memory: C++ copies it; Rust moves it, and a may no longer be used.
Why Rust chose moves: if exactly one variable owns each value, the compiler always knows who must free it and when (section 5), and no hidden second name can change the value under you. Rust then lets you borrow a value: any number of shared, read-only borrows (&T), or exactly one exclusive borrow that may change it (&mut T), never both at once. That single rule, "aliasing or mutation, not both", is what sections 5 and 9 build on.
sharessaved and top are one list; appending through one changes "both". Copying is explicit: top.copy() or list(top).
copiessaved = top copied the vector and every string in it (new memory for each). Sharing is explicit: a reference, std::vector<std::string>& alias = top, is a second name like Python's. The default copy is safe but can be expensive for large values, which is why C++ code passes const T& everywhere.
moves; refusedError E0382, "borrow of moved value": after let mut saved = top; the vector belongs to saved, and using top is a compile error. Nothing was copied (moving a Vec copies three machine words: pointer, length, capacity). The compiler even suggests .clone() if you really wanted a copy.
sharesExactly like Python: both names reach one array. const only stops the name from being re-pointed; the array can still change.
T&); by default the function gets its own copy.const means immutable." In JavaScript, const arr = [] can still be pushed to; in C++ const applies to what it is attached to (the pointer or the thing pointed to); in Rust everything is immutable unless declared mut.std::move is only a cast in C++: ownership, moves and object lifetimes; ownership and borrowing with the Borrow-checker lab in Rust: the essentials; names and aliasing in Python: the essentials, copying and argument passing in Python: the data model and protocols.The axis where the four differ most, and the one Python hides most completely. A value lives at an address, the number of its first byte, printed in hexadecimal (0x10081d500 is 16 bytes after 0x10081d4f0), and a pointer (8 bytes) holds one. A function call's locals sit in its stack frame, freed on return; anything that outlives the call or grows goes on the heap, and "who releases heap memory, and when" is this section's question. The processor reads memory through caches one cache line at a time (128 bytes on this M1 Pro, sysctl hw.cachelinesize; 64 on most Intel and AMD processors), so data that sits together is read almost for free. And a record of a 4-byte user id and an 8-byte count takes 16 bytes in C++ and Rust, not 12: 4 bytes of padding align the 8-byte field (offsetof(Record, tokens) printed 8).
A list of four (user_id, tokens) records drawn at its real addresses, read from the running programs: CPython's object headers through ctypes, C++'s and Rust's with &records[i]. Each row is one 128-byte cache line; rows far apart in memory are separated by a gap. Predict how many cache lines Python touches for four records before you step.
The last step of each view is the consequence, measured on 10 million records (best of several runs, read/code/memory/scan.*): summing the token counts takes ns per record from a contiguous C++ vector and ns from a Python list of tuples. Part of the Python cost is the interpreter (section 2), part the layout: the same compiled C++ loop over one heap object per record, reached through pointers, takes ns per record when the objects happen to sit in allocation order and ns when the pointers are shuffled, about times slower than contiguous: the processor is waiting for cache lines. Shuffling the Python list costs it the same kind of factor ( ns). JavaScript arrays of objects are laid out like Python's (pointers to heap objects), except that V8 stores small integers inside the pointer itself ("Smis", V8 blog).
| Python (CPython) | C++ | Rust | JavaScript, TypeScript (V8) | |
|---|---|---|---|---|
| Strategy | Reference counting, plus a cycle collector for objects that point at each other (gc module) | RAII: a destructor runs when the owning object goes out of scope; containers and smart pointers (std::unique_ptr) do it for you | Ownership: each value has one owner and is dropped when the owner goes out of scope; checked by the compiler | A tracing garbage collector: periodically finds what is still reachable and frees the rest |
| When freed | Immediately at the last reference (cycles: later) | At the closing brace, deterministically | At the closing brace, deterministically | Later, when the collector runs |
| Mistake possible | Leaks through lingering references | Use after free, double free, leaks | Leaks (rare); the rest refused at compile time | Leaks through lingering references |
| Price | A count update on almost every assignment; 16+ bytes of header per object | Your attention | The borrow checker's rules | Pauses and extra memory |
The strategies differ most on one classic bug: keep a reference to the first user's name, then keep adding users, so the list moves to a bigger buffer and frees the old one. Predict what each language does with the reference.
The C++ program compiles without a warning and printed first user: followed by nothing: it read freed memory and carried on (next time it could print garbage or crash). Only AddressSanitizer (-fsanitize=address, compiled in for testing) turns it into a report. Rust refuses the program at the moment of the push, with error E0502: you may not change users while first borrows from it. Python never has the bug: first holds its own reference to the string object, not to the list's slot, and CPython frees the object only when the last reference goes.
Pinned to llama.cpp commit (October 2026). What the code computes (quantisation, attention) belongs to Topic: inference-and-serving and the Quantization and Precision page; here we only read the C and C++. One token's whole path through this code is C++: reading llama.cpp, one token through the code.
1. A struct laid out byte by byte. A 4-bit quantised block of weights: one 2-byte scale and 16 bytes holding 32 four-bit values. The static_assert makes the build fail if the compiler ever added padding. Compiled here, sizeof(block_q4_0) printed: . A weight matrix is a contiguous array of these blocks, so the CPU reads them exactly like the C++ vector above.
2. A tensor is a pointer plus shape plus strides. ggml_tensor is a plain C struct: ne holds the number of elements per dimension, nb the stride in bytes per dimension, and data is a pointer to the first byte. This is the same idea as a NumPy array's shape and strides, with nothing hidden.
3. A memory-mapped file, released by a destructor. llama.cpp does not read a multi-gigabyte model file into memory: it asks the operating system to map the file into the address space (mmap), so the weights are loaded lazily, page by page, as they are touched. The C++ class wraps this in RAII: copying is forbidden (= delete), and the destructor unmaps the file, so it cannot be forgotten.
Python's objects cost memory and speed (128 bytes for 12 bytes of data above) but never a dangling reference. C++'s layout is optimal and its mistakes are silent. Rust has C++'s layout and refuses the mistake, at the price of rules about borrowing that you must learn. Garbage-collected languages trade pauses and memory for simplicity.
std::vector<Record> or Rust Vec<Record> holds the records themselves.del x frees x." It removes one name; the object is freed when the last reference goes. C++'s delete p really frees, whether or not others still point to it.Rc/Arc and RefCell in Rust: lifetimes, smart pointers, threads and unsafe; object sizes and reference counts in Python: CPython internals and performance. The Rosetta tab's "memory" task and "dangling" mistake show the same ideas in the running program. The GPU's own memory hierarchy (registers, shared memory, HBM) is Topic: cuda-and-gpu-programming's subject.Two questions every program meets constantly: what to do when an operation fails (the line is not valid JSON), and how to say "there is no value" (a user with no entry). Python answers both with mechanisms that are invisible in a function's signature: an exception can come out of almost any call, and almost any variable could be None. Rust answers both with ordinary return values whose types say so, which the compiler makes you handle.
None, or an exception.get() returns None, a real object meaning "nothing"; d[k] raises KeyError. Whether you checked is up to you (a type checker can warn when an Optional value is used unchecked).
silently insertsThe false friend of this section: per_user["nobody"] does not fail; it inserts a zero for the missing key and returns it, so the map grew from 1 to 2 entries. Use find() or contains() to ask without changing. C++'s "nothing" for pointers is nullptr, and dereferencing it is undefined behaviour.
refused at compile timeget() returns Option<&u64>: either Some(&value) or None. An Option is not a number, so n + 1 does not compile (E0369); you must say what None means, here with unwrap_or(0). Rust has no null at all in safe code.
refused by tsc, runs to NaNMap.get returns number | undefined. With strict on, tsc refuses the addition (TS18048, 'n' is possibly 'undefined'); run anyway, undefined + 1 is NaN and nothing complains. JavaScript has two "nothings", null and undefined.
The running program has to survive bad lines (the input has eight). Python and TypeScript wrap the parse in try; Rust's serde_json::from_str returns a Result, Ok(value) or Err(error), and C++23 added the same idea as std::expected.
exceptionsDifferent failures arrive as different exception types (here a TypeError and a JSONDecodeError; a missing field would be a KeyError), caught together. Nothing in json.loads's signature says it can raise; you learn it from the documentation or from production.
errors are valuesparse says in its type that it can fail (Result<Message, serde_json::Error>), the ? passes an error up to the caller in one character, and match must handle both Ok and Err or it does not compile. serde also checked the shape (a user that is a number is an error), which Python needed an explicit isinstance for. For bugs rather than expected failures Rust has panic!, which stops the thread (section 10).
expected, uncheckedstd::expected<long, std::string> (C++23, compiled with LLVM clang 23) holds a value or an error, like Rust's Result. But the last line shows the difference in philosophy: *parse_count("94x1") reads the value of an error without any check, which is undefined behaviour, and printed garbage. C++ gives you the vocabulary; Rust makes you use it. Most C++ code, including the standard library, still reports errors with exceptions.
Exceptions keep the happy path short and cost nothing until thrown, but hide which calls can fail. Result and Option make every failure visible in the types and force a decision at every call (the ? operator keeps that cheap to write); the cost is verbosity at the edges, and .unwrap() calls that crash when you guessed wrong.
map[key] fails for a missing key." In C++ it inserts; in JavaScript a plain object or Map returns undefined; only Python raises.panic! is an exception you catch." It is meant for bugs and normally ends the thread; recoverable errors are Results.catch (e) gives me an Error." In JavaScript anything can be thrown, so TypeScript types e as unknown and makes you check.?, thiserror and anyhow in Rust: enums, traits, errors and iterators; exceptions, std::expected and their measured cost in C++: classes, templates and the standard library; exception groups and context managers in Python: the data model and protocols; null, undefined and strict mode in JavaScript: values, objects, functions and modules for Python programmers. The Rosetta tab's "errors" task follows one bad line through the four programs.All four print 0.1 + 0.2 as 0.30000000000000004: they share the same IEEE 754 64-bit floating-point hardware, explained on the Numerical computing for ML page. The running program counts ASCII letters and digits only, so the "what is a character" question never changes its answer; the Rosetta tab shows how each version walks the text (Python by code points, Rust and C++ by bytes, TypeScript by UTF-16 units).
no overflowIntegers grow as needed (263 is fine), // rounds down (floor: -7 // 2 is -4), and a str is a sequence of Unicode code points: len("café 日本 😀") is 9, and s[3] is the whole é.
overflow is undefined behaviourIntegers are fixed-size, and overflowing a signed one is undefined behaviour: the optimised build happened to print the wrapped value, and only the UndefinedBehaviorSanitizer (-fsanitize=undefined) reported it. Division truncates towards zero (-7 / 2 is -3). A std::string is bytes: the same text is 17 bytes, and s[3] is half of the é's two-byte UTF-8 encoding.
checked in debugOverflow panics in a debug build ("attempt to add with overflow") and wraps in a release build, unless you choose explicitly with checked_add (returns an Option) or wrapping_add. Division truncates like C++; div_euclid gives Python's answer. A String is UTF-8 bytes (len() is 17) and cannot be indexed by position at all: s[3] is refused (E0277), because byte 3 is not a character. You iterate .chars() or .bytes() instead.
one float typeEvery number is a 64-bit float, so integers are exact only up to 253 (253 + 1 prints as 253), / never rounds, and BigInt (2n ** 63n) is a separate type. Strings are UTF-16 code units: the emoji counts as 2 (length is 10 for 9 characters) and s[8] is half of it, a lone surrogate.
len(s) is the number of characters" is true only in Python. Rust's len() and C++'s size() count bytes; JavaScript's length counts UTF-16 units.// does; C++, Rust and JavaScript's Math.trunc round towards zero, which differs for negative numbers.int in C++ is like a Python int." It is usually 32 bits, overflowing past 2,147,483,647, and that overflow is undefined behaviour.Polymorphism means one piece of code working with many types. In Python you get it for free by duck typing: total(items) works on anything that has a .tokens() method, and a Protocol lets a type checker verify it. The other three make the requirement explicit, in three different ways.
checked when calledThe Protocol documents the requirement and lets mypy or ty check it; Python itself only fails when .tokens() is called on an int, deep inside total.
checked at compile timeA template is compiled once per type it is used with. A C++20 concept (HasTokens) states the requirement, so the error says "unsigned int does not satisfy HasTokens" instead of a page of template errors. For run-time choice, C++ also has virtual functions and inheritance.
checked at compile timeA trait is opted into explicitly (impl HasTokens for Message); the error E0277 even lists which types do implement it. Generic code (total<T: HasTokens>) is compiled once per type, called monomorphisation; dyn HasTokens is the alternative with one compiled copy and a table of function pointers looked up at run time. Rust has no inheritance.
checked by tsc, by shapeAn interface is structural: any object with a tokens(): number method fits, with no declaration, like a checked Protocol. Calling total([42]) would be refused by tsc. At run time it is plain JavaScript, so the check exists only before running.
Monomorphisation gives the fastest calls and the largest binaries and longest compiles; dynamic dispatch (virtual, dyn, and every Python method call) costs a lookup per call but compiles once. Python and TypeScript need no declarations; C++ concepts and Rust traits make you write the contract down, which is also documentation.
dyn in Rust: enums, traits, errors and iterators; Protocols, decorators and the MRO in Python: the data model and protocols; structural interfaces and type-level code in TypeScript: the type system, narrowing and runtime validation. Metaprogramming in all four is a row of the Design space.A thread shares its program's memory and, on several cores (this laptop has 10), really runs at the same instant as the others. counter += 1 is three steps (read, add one, write back); two threads interleaving them lose an update. Two threads touching the same memory, at least one writing, with nothing ordering them, is a data race. The four languages took four positions on it, and on a second question: how to wait for many slow things at once without a thread for each, which is asynchronous code.
Python's threads are real, but the default build has a GIL: one thread runs Python bytecode at a time; the free-threaded build (3.14t) has none and is officially supported since 3.14 (PEP 779). C++ threads are free and unchecked. Rust's compiler refuses data races through the Send and Sync rules. JavaScript runs your code on one thread around an event loop; worker threads share memory only through a SharedArrayBuffer.
Predict which of six runs gets 4,000,000, then step: the animation runs the same experiment everywhere: four threads each add 1 to a shared counter a million times, so the right answer is 4,000,000. The step-by-step interleaving is illustrative (it shows how an update is lost); every final number is measured on this laptop, three runs each, from read/code/concurrency/.
Read the results together. Python's GIL made this counter come out right in every run, but the Python FAQ is explicit that i = i + 1 is not one of the operations it guarantees to be atomic (Python FAQ); remove the GIL (3.14t) and about 70% of the updates vanish. JavaScript cannot have the bug with ordinary code, because only one piece of your code runs at a time and it is only interrupted at an await; it gets it back as soon as workers share memory. C++ loses updates at -O0 and gets the right answer at -O2 only because the optimiser, allowed to assume no data race, turned a million increments into a single addition: the bug is still there, just hidden. Rust does not let the racy program exist.
The second question has three answers built on the same idea (a task gives its thread back at each await) and different rules about threads, cancellation and blocking. C++ has no standard async runtime: threads, a library such as Asio, or C++20 coroutines as a low-level building block. Only Rust's tokio, by default, spreads tasks over several threads.
| Python asyncio | Rust tokio | JavaScript (Node) | |
|---|---|---|---|
| Calling an async function | Builds a coroutine; nothing runs | Builds a future; nothing runs until it is polled | Runs the body up to the first await |
| Runtime | In the standard library | A crate you add | Built in |
| Threads polling tasks | One per event loop | One per core by default (multi_thread); idle workers steal tasks | One; libuv's pool of 4 threads does file I/O, DNS lookups, some crypto and zlib |
| Fan-out | gather, TaskGroup | join!, JoinSet | Promise.all |
| Cancellation | task.cancel() raises CancelledError at the current await, so finally runs; re-raise it | The future is dropped, so Drop runs; work half done is lost (cancel safety). Dropping a JoinHandle detaches; abort() cancels | None built in: an AbortController's signal, by convention. Aborting is a request; code that never checks the signal runs to the end |
| A blocking call inside | Stalls the loop: every task waits | Ties up one worker thread; the others continue. Blocking work goes to spawn_blocking | Stalls the process: no timer, request or stream moves |
| Shared state across tasks | No data races on one loop (the GIL also serialises threads), but tasks interleave at every await | Must be Send, checked at compile time: a std::sync::Mutex guard held across an .await is refused | No shared memory except between worker threads |
Sources: each row is shown with real runs on Python: concurrency, asyncio and the GIL, Rust: async with tokio, services with axum, and CLIs and JavaScript: the event loop, promises and streams; libuv's pool size from libuv: thread pool.
| Python | C++ | Rust | JavaScript, TypeScript | |
|---|---|---|---|---|
| Memory model | The GIL orders bytecode; without it, built-in objects stay consistent but your updates can be lost | Atomics with explicit memory orders; everything else must be locked | Atomics and locks; Send and Sync say what may cross threads | Atomics on a SharedArrayBuffer, between workers only |
Python's GIL costs parallelism: the Benchmark tab runs the token counter on 4 threads, and with the GIL it is no faster than on 1; the free-threaded build costs some single-thread speed (the Python 3.14 docs give two figures: about 1% on macOS aarch64 to 8% on x86-64 Linux in the free-threading HOWTO, "roughly 5-10%" in What's New in 3.14; on this M1 Pro the Benchmark measured no penalty within run-to-run spread) and needs extensions built for it. C++ costs vigilance and ThreadSanitizer runs. Rust costs wrapping shared state in Arc<Mutex<T>> or atomics, which the compiler demands. JavaScript costs real parallelism: CPU-heavy work blocks the one thread unless moved to a worker.
async makes code run in parallel." In Python and JavaScript it interleaves waiting on one thread; tokio is the exception (above).await, so a read before an await and a write after it can conflict.Send, Sync, Arc and Mutex in Rust: lifetimes, smart pointers, threads and unsafe; microtasks, macrotasks and streams in JavaScript: the event loop, promises and streams; atomics, memory orders and false sharing, measured, in C++: the machine underneath. Locks, futexes and event-driven I/O as the operating system provides them are Concurrency's; the Capacity planning and performance page measured the GIL against free-threaded Python on a server workload; GPU threads (thousands per kernel) are Topic: cuda-and-gpu-programming's. The Rosetta tab's "threads" task counts tokens per user from four threads in all four languages.A language is memory-safe if no program written in it can read or write memory it does not own. Python, JavaScript and safe Rust are; C++ is not. C++'s alternative is undefined behaviour: a list of operations (reading past the end of an array, reading freed memory, overflowing a signed integer, a data race) that the standard declares meaningless. The compiler is allowed to assume they never happen and optimise accordingly, so a program that does one of them may do anything, including appearing to work. The zero-overhead principle is the reason: checking every index costs time, so C++ does not check unless you ask.
Rust is not free of the problem; it fences it. Code marked unsafe may dereference raw pointers and call C, and inside it undefined behaviour is possible again. The point is that it is rare and searchable: the standard library is built on small unsafe cores wrapped in safe interfaces, and tools such as Miri check unsafe code for undefined behaviour. The Rustonomicon is the manual for that part of the language (Further reading).
clear errorIndexError, at the exact line. Every access is checked.
undefined behaviourtop[5] is unchecked: it printed 0, whatever happened to be in memory after the vector. top.at(5) is the checked version and throws. AddressSanitizer turns the unchecked read into a "heap-buffer-overflow" report, 8 bytes after the 12-byte buffer. Compilers and standard libraries now offer "hardened" modes that check [] too; they are opt-in.
checked: panicget(5) returns None; top[5] panics with the length and the index. Indexing is always bounds-checked in safe Rust; the optimiser removes checks it can prove unnecessary (iterators, as in section 2, have none).
silent undefinedJavaScript returns undefined and the arithmetic becomes NaN, no error. tsc lets const x: number = top[5] through unless noUncheckedIndexedAccess is on (the Rosetta program turns it on), in which case it is refused.
unwrap() on None, overflow in debug builds); what they cannot do in safe code is corrupt memory.unsafe, raw pointers and Miri in Rust: lifetimes, smart pointers, threads and unsafe.Who can change a language, and how they avoid breaking your code, explains its pace: Python releases yearly with deprecations over several releases; C++ publishes an ISO standard every three years and almost never breaks anything; Rust releases every six weeks and fixes mistakes through opt-in editions; JavaScript never breaks the web, while TypeScript accepts new errors in minor releases.
Two consequences matter for you. C++ never removes anything, so modern C++ is a subset you choose to write (the C++ Core Guidelines describe it), and old code with old habits stays legal. Rust's editions let it fix mistakes without breaking old crates, because each crate declares its edition in Cargo.toml. TypeScript 7.0 shipped without a programmatic API (expected in 7.1), so tools that embed the compiler, such as typescript-eslint, still run on TypeScript 6 alongside it, as the announcement says.
| Python | C++ | Rust | TypeScript, JavaScript | |
|---|---|---|---|---|
| Who decides | The Steering Council, through PEPs (Python Enhancement Proposals) | The ISO committee WG21, through numbered papers | Rust teams, through RFCs (requests for comments) | JavaScript: the TC39 committee, proposals through stages 0 to 4. TypeScript: Microsoft's team |
| Cadence | One release a year in October (PEP 602) | A standard every three years; compilers adopt features over the following years | A release every six weeks; an edition every three years | An ECMAScript edition each year (TC39 process); TypeScript several releases a year |
| Breaking changes | Deprecations over several releases; rare | Almost never (C compatibility, decades-old code) | Never within an edition; editions opt in per crate and interoperate | JavaScript: never ("don't break the web"); TypeScript: new errors in minor releases are accepted |
Rust and modern Python have one tool that does almost everything (cargo; uv); C++ has many that you assemble, with no standard package manager because compiled libraries must match the compiler and flags they link with; JavaScript has several competing ones. The design-space table above has one row per language.
uv (Astral, written in Rust) installs Python itself, creates environments, resolves and locks dependencies and runs scripts; ruff lints and formats; mypy, pyright or Astral's ty (in beta) check types; pytest tests.-std=.cargo builds, tests, benchmarks, documents, fetches and publishes; clippy lints, rustfmt formats; every published crate's documentation is built on docs.rs. One Cargo.lock pins every version.tsc for checking, and a test runner (vitest, or Node's built-in). Node runs .ts files directly by stripping types since 22.18; that does not type-check, so keep tsc --noEmit in CI.The Benchmark tab times the running program on a 200,000-line log (measured, medians, ): Python 3.14 , Python with a regular expression , TypeScript on Node and on Bun , C++ , Rust . Most of the gap is the interpreter and the layout (sections 2 and 5), and Python closes half of it by pushing the inner loop into C (the regex version). C++ against Rust is not one number: here the C++ version carries its own small JSON parser and the compilers vectorised the loop differently; choose between them for safety and ecosystem, not speed. Start-up and memory matter as much as throughput for command-line tools: Python and Node pay roughly 20 to 30 milliseconds and tens of megabytes before your first line runs (Bun about 6 ms); compiled binaries pay almost nothing.
You rarely rewrite a Python program; you move its hot loop into a compiled extension module, which CPython imports like any module. Rust gets there through PyO3 and maturin (how pydantic-core, tokenizers and polars ship); C++ through pybind11 or its lighter successor nanobind (PyTorch's C++ extensions use pybind11 through torch/extension.h). Measured: the token loop moved into Rust with one call per message took the program from to , and the whole file read in Rust to (nanobind: per call, for the whole file); crossing costs tens of nanoseconds per call, so batch the work. From JavaScript, Rust or C++ compile to WebAssembly or a native Node addon (napi-rs, node-addon-api). And anything calls anything through the C calling convention: a function declared extern "C" in C++ or Rust is callable from almost every language, which is why ggml's core is C (section 1).
| Job | Language | Why |
|---|---|---|
| Research, training, evaluation, notebooks, data wrangling | Python | The libraries are there (PyTorch, NumPy, polars, Transformers), and their fast parts are already C++ or Rust underneath. |
| Make a hot Python loop fast | Rust through PyO3 (or C++ through nanobind in a C++ codebase) | Memory-safe speed; maturin builds wheels; the pattern of pydantic-core, tokenizers and polars. |
| Command-line tools and network services that must be fast, small and reliable | Rust | A single binary, start-up in milliseconds, data races refused at compile time; cargo for everything. |
| LLM applications, agents, MCP servers, anything with a web front end | TypeScript on Node or Bun | The SDKs and harnesses are written in it (section 1); one language from browser to server. Python is a fine second choice for agents. |
| Reading and changing PyTorch internals, llama.cpp, inference engines; writing CUDA kernels | C++ (and C) | That is the language those systems are written in; CUDA C++ is C++ with extensions. |
Each language has an essentials page and four children, written for a Python programmer, every output from a real run. They are listed in the order that pays off soonest for an ML engineer who knows Python: TypeScript (through JavaScript's runtime), Rust, C++, then Python more deeply. Each card keeps its step's milestone, a small program you can show working, closed. Times are each page's own header: core reading, plus its closed details.
JavaScript runs your code on one thread around an event loop, and TypeScript is a type layer erased before anything runs.
undefined rather than an error, this set by the call, and prototype chains.Step 1, closest to Python and immediately useful. The event loop and async/await, objects as shared references, null, undefined and strict mode, then types: narrowing, unknown, and validating input at the boundary because types are erased. Milestone: an MCP server in TypeScript that exposes the token counter as a tool.
Every value has one owner and every borrow is checked at compile time, so memory and data-race bugs become compile errors.
Step 2, ownership first. Ownership, moves and borrowing (chapter 4 of the Rust Book), then Option and Result, traits, cargo and clippy. Milestones: the token counter as a PyO3 extension called from Python and timed against the Python loop; then the same as a command-line tool; then a small HTTP service with tokio.
You decide where each object lives and when it dies, and the compiler trusts you: files compile separately and link, and a broken rule is undefined behaviour.
Step 3, from the machine up, to reading llama.cpp. The goal is to read real inference-engine source, so learn the features in the order that code uses them (the seven steps below). Milestones: the token counter in C++ under AddressSanitizer with no reports; then build llama.cpp from source, run a small GGUF model, and count which kernels actually run: on an Apple Silicon Mac with the default build, the ggml_vec_dot_* functions most guides point to run zero times, because the weights are repacked at load and 4x4 gemv/gemm kernels do every product (measured on C++: reading llama.cpp, one token through the code). Reading the scalar ggml_vec_dot_q4_0_q8_0 next to its NEON version is still the best way into ggml's SIMD code. Then CUDA, which is Topic: cuda-and-gpu-programming's path, and what llama.cpp's kernels compute (attention, KV cache, quantisation), which is Topic: inference-and-serving's.
Counts at llama.cpp commit , from read/code/llama/excerpts.sh.
void* casts. ggml_tensor and block_q4_0 (section 5) are plain C structs; the CPU kernels walk arrays of blocks through pointers (x[ib].qs[j]).mmap (section 5), and reading a binary format (the GGUF reader is ggml/src/gguf.cpp).#if/#ifdef select code per processor and backend (50 such lines in the ARM CPU kernel file alone) and macros such as GGML_RESTRICT.ggml-cpu/quants.c) and per-architecture versions full of NEON calls like vld1q_u8 (209 vld1q_ calls in arch/arm/quants.c). Read the scalar one first; it says what the SIMD one computes.pthread_create behind a ggml_thread_create macro; the data-race rules of section 9 apply.src/: classes and RAII (llama_mmap's destructor), std::unique_ptr (60 uses in the headers), std::vector and std::string, lambdas, exceptions (260 throw std::runtime_error), then templates (58 declarations; read, rarely written).GGML_CUDA, GGML_METAL, GGML_VULKAN, GGML_HIP, GGML_SYCL, GGML_BLAS), and sanitizers for your own changes.A name is a reference to an object, and every piece of syntax is a method call on its type, run as bytecode by one interpreter.
with and attribute access is a special-method lookup on the type, with fixed fallbacks.Step 4, deeper (you already use it daily): the object model and data model protocols, what CPython does with your code, packaging with uv, free-threaded 3.14 and the changes in 3.15. Milestone: profile a slow script, then make it faster three ways (algorithm, vectorised library, extension) and explain each gain.
| Axis | Python: readability | C++: zero overhead, C compatibility | Rust: safety without a GC, at compile time | TypeScript: erasable types over JavaScript |
|---|---|---|---|---|
| How code runs | An interpreter: no compile step to think about | Ahead-of-time machine code, nothing at run time | Ahead-of-time machine code, checks done while compiling | Types erased, so JavaScript runs unchanged |
| Types | Dynamic; hints optional and outside the language | Static, so the compiler can lay out and inline | Static and strict: the compiler needs the facts to prove safety | Static but structural and unsound, to fit existing JavaScript |
| b = a | Share: names, not boxes, are simplest to read | Copy, as C does with structs | Move: one owner, so freeing is provable | Share, as JavaScript does |
| Memory | Reference counting: invisible to the reader | RAII: deterministic, no collector to pay for | Ownership: RAII made checkable | JavaScript's garbage collector |
| Errors, nothing | "Errors should never pass silently": exceptions | Exceptions, or no checks at all where they cost | Result and Option: failure visible in types | JavaScript's exceptions; strict null checks added on top |
| Numbers, text | Big ints and code points: what a reader expects | Machine integers and bytes: what the hardware does | Machine integers, checked in debug; UTF-8 that cannot be misindexed | JavaScript's doubles and UTF-16, kept for compatibility |
| Abstraction | Duck typing: nothing to declare | Templates: generic code with no run-time cost | Traits and monomorphisation: generic, fast and checked | Structural interfaces: describe existing JavaScript shapes |
| Concurrency | The GIL kept the interpreter simple; now optional | Threads with no hidden cost, and no protection | Send and Sync: data races are type errors | One thread and an event loop, as browsers require |
| Safety | Everything checked at run time | Undefined behaviour instead of checks | Safe by default; unsafe fenced and searchable | Memory-safe JavaScript; types may lie |
| Evolution | Yearly, with deprecations | Never break old code | Editions: fix mistakes without breaking crates | "Don't break the web"; TypeScript moves faster |
This tab is the comparison core of the topic. Every row is a design question (an axis), every column a language, and Python is the reference column, because experienced programmers learn a new language by mapping it onto the one they know, and go wrong exactly where the mapping breaks: Shrestha, Botta, Barik and Parnin found 276 such cases of interference in 450 Stack Overflow questions across 18 languages, and interviewed programmers who "make failed attempts to relate a new programming language with what they already know" (ICSE 2020, doi 10.1145/3377811.3380352). Comparing worked solutions side by side helps conceptual learning (Rittle-Johnson and Star 2007). So each cell gives the language's choice, a small real program with its real output or real compiler error, what the choice buys and costs, and the founding value it comes from. The False friends view collects the places where Python habits mislead.
The same small tool written in Python, C++, Rust and TypeScript, read line by line with Python as the reference. Every snippet on this tab compiles and runs; every output, compiler error and type-checker message below is the real text, captured by running the code (versions at the bottom).
The tool: read a chat log in JSONL (one JSON object per line), count the word-ish tokens in each message, add them up per user, print the five heaviest users. It is the kind of throwaway script an ML engineer writes weekly, and it touches files, parsing, text, a hash map, sorting, and bad input. The input is a seeded, generated log of 2,000 lines, 8 of them deliberately malformed; three lines of it:
Token rule: a run of ASCII letters or digits ([A-Za-z0-9]+), so x86_64 is 2 tokens and 日本語 is 0. Sort by count, ties by user id. The full spec, the generator and the expected output are in the page's source folder (src/rosetta/PROGRAM.md); the Benchmark tab times this same program.
Pick the program or a focused task, then a language. Annotated puts a plain-words note beside each block of code, with the Python bridge; Side by side sets two languages next to each other.
Eight timestamps from the log, summed one by one. A Python list does not hold numbers: it holds 8-byte pointers to separate 32-byte int objects, wherever the allocator put them. A NumPy array, a C++ std::vector<int64_t> and a Rust Vec<i64> hold the eight numbers themselves, side by side. The addresses drawn are the real ones printed by the programs in Where the numbers live above; a CPU fetches memory in 64-byte cache lines, so the counter of lines touched is the cost that matters. The walk opens finished; step back and forward through it read by read with the controls. The same layout for whole records, with a scan of 10 million of them measured, is Reading, section 5.
What this does not show: the CPU's prefetcher hides much of the cost of a predictable walk, and the interpreter's own work per element (type checks, reference counts) is usually larger than the memory cost for eight numbers. At millions of elements both matter; the Benchmark tab measures the whole program.
Six bugs a Python programmer is likely to write in the other three languages, each written in all four. The colour says what really happened when we compiled and ran it; click a cell for the code, the exact message and what it means.
Every output on this tab was produced by src/rosetta/run_all.sh, which rebuilds each snippet, runs it, checks that the four programs print exactly the expected output, stores each capture in src/rosetta/outputs/ and regenerates this tab's data. Machine-specific paths are shortened (<python>, <llvm>); memory addresses and thread ids change on every run.
The Rosetta tab's count_tokens program (read a JSONL chat log, count word-ish tokens per user, print the top five), run on a realistic input in every language this page covers, plus the ways Python can call Rust or C++ to go faster. Every number on this tab was measured on one laptop on and is read from the raw results in src/bench/results/; a script checks that they match.
Input: the Rosetta generator with --lines 200000 --seed 7: lines, MB, valid messages holding characters of text and tokens, plus 8 malformed lines. Every variant printed exactly the expected output before it was timed. Machine and versions are under Method and caveats.
re module.json.loads still runs; moving the whole file into one Rust call gave , of which about is just starting Python, and with four Rust threads , faster than the single-threaded Rust program.A speed difference is only useful if you know where it comes from, because that tells you what a rewrite would buy. Each box below takes one cause, shows it measured on this program, and says what it costs.
CPython runs tokens() as bytecode on objects (every character a one-character str, every comparison a bool); Rust and C++ run machine code on raw bytes in registers. Measured over the whole file, the Python loop spends per character, the compiled C++ loop per byte and Rust's per byte; the real -O2 build handles bytes per pass with SIMD instructions. Note also é: one character for Python, two bytes for C++ and Rust, which work on UTF-8 bytes. The instructions each route executes per character are stepped through in the Reading tab, section 2; why CPython pays this per element, and how to move the loop out of Python, is Python: CPython internals and performance.
Before rewriting anything, measure which part is slow. src/bench/py/breakdown.py times each stage of the reference program as its own pass over the 200,000 lines:
The character loop is the biggest stage, so it is the first target; the regex version replaces it with C code and saves most of it. But json.loads stays: it is already written in C, and what it costs is building Python objects, a dict and several str objects per line, each a heap allocation with a header and a reference count. That is why the Python + Rust "one call per message" variant cannot go below the cost of parsing in Python.
Python stores every value as a boxed object on the heap (a header with a reference count and a type pointer, then the value), even a small integer or a one-character string. Rust and C++ keep a count in a register or an 8-byte slot. Peak memory (maximum resident set size, from /usr/bin/time -l) on the full input:
Most programs here stream the file line by line and stay small. Three kinds hold more: the threaded Python variants read every line first so they can split them (200,000 str objects at once, MB), the "one call for all messages" variants keep every message in a list before the call ( MB), and the Rust extension's whole-file call reads the 39 MB file into one buffer ( MB). Node and Bun carry a JIT compiler and a garbage-collected heap ( and MB); the Rust and C++ binaries need and MB. The interpreter itself has a floor: CPython MB for the plain loop; on the empty file it starts in , and most of that memory is the interpreter and its imported modules rather than the data.
The same token loop, timed alone on a 120-byte string (src/bench/loop_probe.sh):
Same algorithm, different machine code. Apple clang 14 (the compiler this Mac ships, from 2022) vectorises the loop but fills its vector registers one byte at a time ( single-byte loads per iteration); rustc 1.99 (LLVM ) loads bytes per iteration in two 16-byte registers; LLVM clang 23 compiling the very same C++ source runs at per byte, faster than the Rust loop. Writing the test as (c | 32) - 'a' < 26 || c - '0' < 10 (fold upper to lower case, one range check each) brings Apple clang 14 to . Lesson: "C++ vs Rust" on a tight loop is mostly "which compiler version, which idiom"; both languages reach the same machine code, because both are compiled by LLVM.
But the loop is not why the whole C++ program is slower than the Rust one. At the measured speed, counting the characters of text costs about in C++ (characters times nanoseconds per byte; slightly more bytes than characters, so a slight underestimate) out of . The rest is reading lines with std::getline into a std::string, the Rosetta tab's small hand-written JSON parser (which builds a new std::string for each field), and the hash map. The Rust version uses serde_json, a parser tuned over years, deserialising straight into a typed struct. Two more C++ builds separate the causes. The same Rosetta source compiled by LLVM clang 23 (2026) against the same standard library took : the newer compiler alone changes little. Swapping the hand-written parser for simdjson 3.13.0 (a widely used parser that checks many bytes at once with SIMD instructions), same Apple clang 14, took (a benchmark-only variant in src/bench/cpp_simdjson/), against Rust's . The gap that is left is mostly std::getline copying every line and std::unordered_map keyed by freshly built strings. So "C++ is slower than Rust" on this page means "this C++ program, with a small teaching parser"; the language does not force it.
Every call into an extension converts its arguments from Python objects and boxes its result back. Measured in-process with timeit (median of 7 repeats of calls), the empty call and the cost per message (average characters, messages):
The call is cheap next to a Python loop over the characters (tens of nanoseconds against microseconds), and the batched call is cheaper per message because the loop over messages moves into native code too; the differences between PyO3, pybind11 and nanobind in the batched rows are mostly the token loop's machine code (box 4), not the binding. Borrowing a str instead of copying it, batching, and releasing the GIL are taught step by step in Rust: speeding up Python with PyO3 and maturin.
The same threaded program on the full input, in the standard build (with the GIL) and the free-threaded python3.14t (PEP 703 and PEP 779):
With the GIL, four threads are no faster than one. Without it, four threads were faster than one and eight threads , not 4 and 8: reading the file and merging the per-thread counts still run on one thread, and the machine had other work running (see Method and caveats). The plain loop took on 3.14t against on 3.14, within the run-to-run spread; the build pays for thread-safe reference counting and per-object locking (PEP 703), which the CPython team puts at roughly 5 to 10% on single-threaded code (external box below). Rust threads inside the extension (py.detach releases the GIL) took against on one thread. What the GIL guarantees, what the free-threaded build costs and when to use processes or subinterpreters instead are Python: concurrency, asyncio and the GIL's subject; the capacity planning page measured the same effect on a different workload.
str objects of code points as it reads; JavaScript strings are UTF-16; C++ std::string and Rust's String keep the UTF-8 bytes (Rust checks they are valid UTF-8, C++ does not). The compiled loops count over bytes, which is correct here only because every non-ASCII byte is 0x80 or above (PROGRAM.md, rule 3).open, C++ std::ifstream, Rust BufReader, Node's read stream), so the 39 MB arrive in large chunks rather than one system call per line. Reading and splitting the lines took Python : I/O is not the bottleneck for any variant. Output is five lines, so stdout buffering does not matter here; it would for a program that prints a line per record.-c pass) and Node (Startup view above). For a command-line tool run thousands of times by a script, that floor can matter more than throughput. A cold bytecode cache costs Python more: against when every imported module must be compiled again (it happens once, after an install or upgrade). Node's compile cache made no measurable difference to this small script ( against ), and running the .ts file directly cost at startup against for the compiled .js.countTokens to machine code using the types it has seen (just-in-time compilation). That is why Node is far faster than CPython on the character loop while starting slower than a native binary. CPython 3.14 has an experimental JIT too, built but switched off in the interpreter measured here (--enable-experimental-jit=yes-off).Other people's measurements on other machines and workloads, quoted with their date. They are context for the measurements on this tab, never mixed into its charts.
| Claim | Source, date | Measured on |
|---|---|---|
| "The performance penalty on single-threaded code in free-threaded mode is now roughly 5-10%, depending on the platform and C compiler used." | What's New in Python 3.14, October 2025 | Not stated; CPython core team |
| Tail-call interpreter: "a geometric mean of 3-5% faster on the standard pyperformance benchmark suite", baseline 3.14 built with Clang 19 without it; "only works with Clang 19 and newer on x86-64 and AArch64" | What's New in Python 3.14, October 2025 | pyperformance; the interpreter measured here was built with it (--with-tail-call-interp) |
| nanobind against pybind11: compile time "~2.7-4.4× improvement", binary size "3-5× improvement", runtime overhead "~3× improvement for simple functions" | nanobind documentation, Benchmarks; undated, nanobind 1.2.0 (about early 2023); written by nanobind's author, so a vendor claim | AMD Ryzen 9 7950X, Ubuntu 22.04.2, clang++ 15.0.7 |
| TypeScript's native (Go) compiler: "reduce most build times by 10x"; VS Code's 1,505,000 lines checked in 7.5 s against 77.8 s (10.4×) | A 10x Faster TypeScript, Anders Hejlsberg, 11 March 2025; vendor claim. The tsc measured here is that compiler, | Not stated in the post |
Node.js runs .ts files directly by stripping the types: "Node.js will be able to execute TypeScript files without additional configuration" | Node.js 22.18.0 release notes, 31 July 2025 | Feature, not a number; the "types stripped" row above uses it |
How the nanobind claims look on this machine: the per-call overhead of an empty function was for nanobind against for pybind11 (), and the extension files were KB against KB: nanobind's file is larger here because this build compiles its whole runtime (nb_combined.cpp) into one tiny module; its size advantage shows on large bindings.
-N), output discarded.purge), so a cold-disk start was not measured. What was measured cold is the language runtime's own cache: Python with an empty bytecode cache (every imported module compiled from source again) and Node with an empty compile cache; see the Startup view./usr/bin/time -l, maximum resident set size, median of 3 runs.-c pass, -e 0).src/bench/loc.py. The C++ count includes the -line JSON parser (json_lite.hpp) the C++ version must carry because the standard library has none; the Rust count includes Cargo.toml but not serde_json.main.rs.Reproduce: PL=<toolchains> WORK=<scratch dir> bash src/bench/run_bench.sh (about 6 minutes) regenerates every raw file in src/bench/results/, then summarize.py writes the data this tab reads and check_numbers.py checks the page against it. src/bench/README.md lists the toolchain installs.
Every job a project needs done, from installing the language to calling the other three, and the tool each ecosystem uses for it, with the version that was current on 2026-10-05, the official page it was read from, and the one command a beginner types. Python is the reference: every other cell says what the Python equivalent is, and where the analogy breaks.
Try: click a cell to open it below; untick languages to narrow the grid; type a tool name to find where it sits.
Each walkthrough was run for real on 2026-10-05 in an empty folder; the output is the actual terminal output, trimmed only where marked. The same tiny program in every language: count runs of ASCII letters and digits in "Hello from hello-tokens, x86_64 café!", which prints 7 (the é splits café, the underscore splits x86_64).
Standards, editions and releases on one axis. Filled marks happened; hollow ones are scheduled. Click a mark for what changed and its source.
The old Notion pages were treated as unverified notes. Every tooling, version and schedule claim in them was checked against the official source on 2026-10-05; this is what changed. Full table with sources: src/tools/corrections.md.
Every link checked on 2026-10-05. Times are estimates for a first useful pass, not for the whole resource; "when" says at which step of the learning path (the language cards at the end of the Reading tab) to open it.
(19 min, plus 11 in closed details) Then: JavaScript: values, objects, functions and modules for Python programmers (28 min, plus 11 in closed details); JavaScript: the event loop, promises and streams (19 min, plus 11 in closed details); TypeScript: the type system, narrowing and runtime validation (30 min, plus 49 in closed details); TypeScript: LLM apps and agents (25 min, plus 25 in closed details).
(31 min, plus 11 in closed details) Then: Rust: enums, traits, errors and iterators (39 min, plus 18 in closed details); Rust: lifetimes, smart pointers, threads and unsafe (21 min, plus 14 in closed details); Rust: speeding up Python with PyO3 and maturin (38 min, plus 13 in closed details); Rust: async with tokio, services with axum, and CLIs (31 min, plus 19 in closed details).
(21 min, plus 9 in closed details) Then: C++: ownership, moves and object lifetimes (21 min, plus 13 in closed details); C++: classes, templates and the standard library (25 min, plus 17 in closed details); C++: the machine underneath: caches, layout, SIMD and the memory model (33 min, plus 21 in closed details); C++: reading llama.cpp, one token through the code (37 min, plus 39 in closed details).
(12 min, plus 1 in closed details) Then: Python: the data model and protocols (28 min, plus 21 in closed details); Python: concurrency, asyncio and the GIL (19 min, plus 10 in closed details); Python: CPython internals and performance (23 min, plus 6 in closed details); Python: typing, uv, packaging and the toolchain (22 min, plus 15 in closed details).
The running program in four languages, line by line, with focused tasks and deliberate mistakes. (20 min)
Every axis by every language, a runnable snippet per cell, and the full false-friends collection. (30 min)
Speed, memory, start-up, compile time and the cost of crossing from Python into Rust or C++, measured. (15 min)
The tools of each ecosystem, their versions and what each replaces. (15 min)
Kernels, CUDA C++'s extensions, the GPU memory hierarchy, Triton, CUTLASS, and Rust on the GPU. The next stop after this page's C++ path. (28 min read)
What engines such as llama.cpp and vLLM compute: KV cache, batching, quantised kernels in production. (page)
PyTorch's C++ core, custom operators and torch.compile. (page)
Where the TypeScript path leads: agent harnesses and MCP. (pages)
The same chat product seen as a system; its children Building a backend API (32 min), Code design (42 min), Testing and quality (46 min) and Capacity planning and performance (39 min, with the GIL against free-threaded Python measured). (33 min)
Floating point and precision formats: why 0.1 + 0.2 prints the same in all four languages. (40 min)
What llama.cpp's quantised blocks mean, and the C++/CUDA machinery of training at scale. (about 23 and 22 min)
Python Software Foundation, kept current with each release (3.14 when checked). For: filling gaps in the basics. When: only if a section of this page used something unfamiliar. (2 h; skim)
For: how every operator and built-in dispatches to dunder methods; the core of the "Python, deeper" step. When: step 4. (1 h)
October 2025 release notes, plus the free-threaded build's costs and status. When: before using threads for CPU work. (45 min)
The community reference for the language and standard library, with the version each feature appeared in and compiler support tables. For: looking things up, precisely. When: from the first day of step 3. (lookup)
Bjarne Stroustrup, Addison-Wesley, September 2022; covers "C++20 plus a few likely features of C++23". For: the whole modern language in 254 pages, from its designer, for "experienced programmers". When: after the C basics of step 3a. (8 h)
Stroustrup and Sutter, continuously updated. For: which subset of C++ to write (RAII, ownership, no naked new). When: while writing your first C++ milestone. (2 h for the "P", "R" and "ES" sections)
LLVM documentation for the tools that produced the reports on this page. When: before your first C++ program with pointers. (20 min)
See the machine code of any snippet under any compiler, as section 2 did locally. When: whenever you wonder what an abstraction costs. (tool)
The reading target of step 3; this page pinned commit 8e1642198dcd (5 October 2026). Start at ggml/include/ggml.h and ggml/src/ggml-cpu/quants.c. When: end of step 3. (weeks, in pieces)
Klabnik, Nichols and Krycho; the current online text assumes Rust 1.97.0 (2026-07-09) or later and the 2024 edition. For: learning the language; chapter 4 (ownership) is the one that matters most. When: step 2, first. (15 h)
Runnable examples, and small exercises that the compiler grades. When: alongside the Book. (4 h and 8 h)
PyO3 0.29.3 when checked. For: writing Python extensions in Rust and building wheels. When: the first milestone of step 2. (2 h)
The official guide to unsafe Rust: what undefined behaviour means in Rust and how to build safe abstractions over raw pointers. When: only once you need unsafe or FFI. (3 h)
What each edition and six-weekly release changed. When: when code from an older tutorial does not compile. (20 min)
Mozilla's reference, continuously updated. For: the language itself, and how the event loop, tasks and microtasks work. When: step 1, before TypeScript. (4 h)
Microsoft's official guide. For: everyday types, narrowing, generics; read "Everyday Types" and "Narrowing" first. When: step 1, after the JavaScript runtime. (4 h)
The native compiler release of 8 July 2026, and the goals and non-goals quoted in section 1. When: when setting up a project. (25 min)
What Node's type stripping does and does not do. When: your first node file.ts. (15 min)
The JavaScript specification and how features reach it. When: to settle an argument about behaviour. (lookup)
Why experienced programmers struggle with a second language: interference from the first. The reason for this page's false-friends boxes. (30 min)
Teaching a new language through equivalent Python code. (20 min)
The usage figures of section 1. (15 min)