Topic: programming-languages

Python, C++, Rust and TypeScript compared on one small program: what each decides differently about running, types, memory, errors, concurrency, tooling and speed, and a map of the sixteen pages that teach each language. Data as of October 2026. Reading: 40 min, plus 20 in closed details.

The four languages on one map

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

  1. One program, four lanes. The running program below, written as 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.
  2. Where each language catches a mistake. The same bug (red) runs down each lane until something stops it. TypeScript, while you edit: tsc refuses wrong types, missing fields, values that may be absent; then the types are erased. Rust, when it compiles: no program is produced until types, ownership, borrowing, data races and unhandled cases pass. Python, when it runs: every operation checked, an exception at the line that did it. C++ compiles types, missing functions and template constraints, not memory or races: out of bounds, use after free, signed overflow and data races are undefined behaviour, and the program carries on, possibly wrong. Dashed: each lane's weaker moment (Python only if you annotate and run mypy, pyright or ty; Rust a panic for bounds, failed unwrap, overflow in debug builds; wrong types from JSON.parse pass in TypeScript, and undefined + 1 is NaN). Sections 3, 6 and 10.
  3. How code runs. CPython compiles to bytecode that a loop in C interprets, 29 bytecode instructions per character of the token loop; clang and rustc hand the code to LLVM, which emits 16 and 17 machine instructions per byte, then a SIMD loop over 8 and 32 bytes at a time; tsc erases the types and V8 interprets the JavaScript, then JIT-compiles the hot function after watching its types. Section 2 steps through the real output.
  4. Who frees memory. CPython counts references on every object and frees each at its last reference; C++ runs destructors at the closing brace (RAII), and you must get it right; Rust frees at the owner's closing brace, with every borrow checked by the compiler; V8's tracing garbage collector frees later. Python's records are scattered objects, C++'s and Rust's sit side by side: summing 10 million records took ns per record from a Python list and ns from a C++ vector (measured, section 5).
  5. Threads. Four threads each add 1 to one counter a million times. Python with the GIL got 4,000,000; C++ at -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).
  6. One task, measured. The running program on a 200,000-line log, median wall time: Python 3.14 , C++ , Rust , TypeScript on Node (measured, Apple M1 Pro). Section 12 and the Benchmark tab say where each gap comes from.

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.

New terms

Founding value: the goal a language's designers kept when two goals conflicted (section 1)
Ahead-of-time, bytecode, JIT: the three routes from source to machine code (section 2)
Static, dynamic, gradual typing: types checked before running, while running, or where annotated (section 3)
Ownership, borrow: Rust's one owner per value and its checked loans (sections 4 and 5)
RAII: a destructor frees what an object owns when it goes out of scope (section 5)
Undefined behaviour: an operation C++ gives no meaning to; the compiler may assume it never happens (section 10)
GIL, event loop: CPython's one-thread-at-a-time lock, and JavaScript's one-thread scheduler (section 9)
Extension module: a compiled library CPython imports like a module (section 12)

The design space in one screen

PythonC++RustTypeScript
Founding valueReadability: "Readability counts"Zero overhead, and compatibility with CMemory and thread safety checked before the program runs, with no garbage collectorJavaScript plus types that disappear; never break existing JavaScript
In ML work todayThe glue and the research languageThe substrate: PyTorch's core, CUDA kernels, llama.cppThe new substrate of Python's tools (uv, ruff, tokenizers, polars) and fast servicesLLM apps, agents, MCP servers, coding harnesses
How code runsCompiled to bytecode, interpreted; hot code specialisedCompiled ahead of time to machine codeCompiled ahead of time to machine code (LLVM)Types erased, then V8 interprets and JIT-compiles the JavaScript
TypesDynamic; optional hints checked by separate toolsStatic, by nameStatic, by name, strongly inferredStatic, by shape, gradual, unsound on purpose
b = a meansShare the objectCopy itMove it (a is now unusable)Share the object
Memory freed byReference counting plus a cycle collectorYou, through destructors (RAII)The owner going out of scope, checked by the compilerA tracing garbage collector
Errors, nothingExceptions; NoneExceptions or std::expected; nullptrResult and Option values; panic for bugsExceptions; null and undefined
Integers, stringsUnbounded ints; code pointsFixed ints, signed overflow is undefined behaviour; bytesFixed ints, overflow panics in debug; UTF-8, no indexing64-bit floats plus BigInt; UTF-16 units
AbstractionDuck typing, ProtocolsTemplates and concepts; virtual functionsTraits; generics or dynStructural interfaces, generics
ThreadsGIL by default; free-threaded build supported since 3.14Free; data races are undefined behaviourFree; data races refused at compile timeOne thread and an event loop; workers for more
Waiting for I/Oasyncio: one event loopThreads, or a library (Asio)async with a runtime you add (tokio), on several threadsBuilt in: the event loop and promises
When you get it wrongAn exceptionUndefined behaviour: anything can happenA compile error, or a panicA runtime exception, or a silent NaN
ReleasesYearlyISO standard every three yearsEvery six weeks; editionsJavaScript yearly; TypeScript several times a year
Toolchainuv for interpreters, environments and locks; ruff; a type checkerA compiler, CMake, sanitizers; no standard package managercargo does everything; clippy, rustfmtA 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.

How this page was made, and why it ends each section with false friends (optional)

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.

1. Four philosophies

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.

Python (early 1990s)

"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).

C++ (1985)

"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).

Rust (1.0 in 2015)

"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.

JavaScript (1997 standard) and TypeScript (2012)

"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.

Four layers of one ML stack, not four competitors

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.

The layers in numbers: byte shares, contributor counts and llama.cpp's C and C++ split (optional, dated)
  • Python. Hugging Face Transformers is 99.9% Python by bytes. GitHub's Octoverse 2025 counts 2.6 million monthly contributors to Python and calls it "dominant for AI and data science workloads" (GitHub, 28 Oct 2025).
  • C++. PyTorch is two thirds Python by bytes, but the tensors, the autograd engine and the CPU kernels underneath are C++ (26%) and CUDA. ONNX Runtime is 83% C++. In llama.cpp the tensor library 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.
  • Rust. uv (98% Rust), ruff (97%), Hugging Face tokenizers (95%) and safetensors, polars (63%) and pydantic-core are Rust compiled into Python packages. OpenAI's Codex CLI is 97% Rust. The Stack Overflow 2025 survey found Rust "yet again the most admired programming language (72%)" and uv the most admired technology among its tags (74%) (Stack Overflow, 2025). Since September 2026 Rust can also write NVIDIA GPU kernels, which belongs to Topic: cuda-and-gpu-programming.
  • TypeScript. The official MCP TypeScript SDK, Vercel's AI SDK, Google's Gemini CLI, OpenAI's Agents SDK for JavaScript and Anthropic's TypeScript SDK are all 85 to 99% TypeScript. In August 2025 TypeScript overtook Python and JavaScript as the most used language on GitHub by monthly contributors (2,636,006), which GitHub links partly to AI-assisted coding preferring typed code (Octoverse 2025).
  • Mojo, Modular's Python-like language for accelerators, is not one of the four here; its compiler was released under Apache 2.0 on 18 August 2026, a week after its 1.0.
False friends for a Python programmer (2)
  • "JavaScript and TypeScript are two languages." TypeScript is JavaScript plus a type checker; whatever runs is JavaScript. Learning TypeScript means learning JavaScript's runtime first.
  • "C++ is C with extras." Modern C++ code that follows the C++ Core Guidelines uses almost none of C's habits (raw arrays, manual malloc). llama.cpp is unusual in mixing both, which is why reading it needs both (C++: reading llama.cpp).

2. How code runs

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).

  • Ahead-of-time compilation (C++, Rust): a compiler translates the whole program before it runs. Both clang and rustc hand their work to LLVM, the same optimiser and code generator.
  • Bytecode plus an interpreter (CPython): Python compiles your file into bytecode, then a loop written in C, the interpreter, executes one instruction at a time. Since 3.11 it rewrites hot instructions into type-specialised forms while the program runs (PEP 659).
  • Interpret first, compile the hot parts (JavaScript in V8): V8 runs bytecode in its Ignition interpreter, watches which types flow through each function, and compiles hot functions with its optimising compilers (Sparkplug, Maglev and TurboFan; V8 blog). This is a JIT, a just-in-time compiler; when a guess fails (a new type arrives) it throws the machine code away, a deoptimisation.
  • Erase, then run as JavaScript (TypeScript): 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.

    What "compile time" buys, what each route costs, and false friends (4)

    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 byPythonC++RustTypeScript
    TranslationSyntax errors onlyTypes, missing functions, template constraintsTypes, ownership, borrowing, data races, unhandled casesTypes (then erased)
    A separate checkermypy, pyright, ty: types, if you annotateclang-tidy, sanitizers (at run time, in tests)clippy: style and likely bugstsc is the checker
    Run timeEverything else, as exceptionsLittle: most mistakes are undefined behaviour, not errorsIndex out of bounds, overflow in debug builds, failed unwrap: a panicJavaScript'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.

    • "Python is interpreted line by line." It is compiled to bytecode first (you have seen the .pyc files in __pycache__); only the bytecode is interpreted.
    • "TypeScript is compiled, so it is fast like C++." Its compilation removes types; the speed is V8's, the same as JavaScript.
    • "Python 3.14 has a JIT, so loops are fast now." The JIT ships in the official macOS and Windows installers but is experimental and off unless you set PYTHON_JIT=1 (What's new in 3.14); the 3.14 run above shows JUMP_BACKWARD_NO_JIT.
    • "An optimised build is the same program, faster." In C++ optimisation can change what a buggy program does (section 9 shows a data race that disappears at -O2); in Rust, integer overflow panics in a debug build and wraps in a release build (section 7).
    Go deeper: CPython's bytecode, the specialising interpreter and the JIT in Python: CPython internals and performance; what the compiled loop does on the CPU (caches, SIMD, reading assembly) in C++: the machine underneath; V8's tiers in JavaScript: values, objects, functions and modules for Python programmers; erasure on a real file in TypeScript: the type system, narrowing and runtime validation. Compiler flags and runtimes are in the Toolchain atlas; start-up and warm-up are measured in the Benchmark.

    3. Types

    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.

    What each choice costs, and false friends (3)

    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.

    • "Type hints make Python check types." They do not; only a separate tool does. The same is true of TypeScript at run time: a 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.
    • "Rust's u64 is like Python's int." It is a fixed 64-bit unsigned integer; section 7 shows what happens at its limit.
    Go deeper: hints and the type checkers in Python: typing, uv, packaging and the toolchain; narrowing, generics, conditional and mapped types and runtime validation with zod in TypeScript: the type system, narrowing and runtime validation; enums and traits in Rust: enums, traits, errors and iterators. Nominal against structural, variance and soundness holes are one row each in the Design space.

    4. Names, values and mutation

    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.

    False friends (3)
    • "Passing a vector to a C++ function lets it change my vector." Not unless the parameter is a reference (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.
    • "Rust's move is like Python's assignment." It is closer to handing over the only key: the old name is dead.
    Go deeper: copies, moves, the rule of five and why 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.

    5. Memory and lifetimes

    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).

    The same four records, in Python and in C++ or Rust

    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).

      Why NumPy and PyTorch are fast from Python
      A NumPy array or a PyTorch tensor is one Python object that owns a contiguous C buffer, laid out like the C++ vector above. The loop over it runs in C or C++, so neither the interpreter nor the pointer-chasing is paid per element. That is the whole trick behind "vectorise your Python".

      Who frees memory, and when

      Python (CPython)C++RustJavaScript, TypeScript (V8)
      StrategyReference 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 youOwnership: each value has one owner and is dropped when the owner goes out of scope; checked by the compilerA tracing garbage collector: periodically finds what is still reachable and frees the rest
      When freedImmediately at the last reference (cycles: later)At the closing brace, deterministicallyAt the closing brace, deterministicallyLater, when the collector runs
      Mistake possibleLeaks through lingering referencesUse after free, double free, leaksLeaks (rare); the rest refused at compile timeLeaks through lingering references
      PriceA count update on almost every assignment; 16+ bytes of header per objectYour attentionThe borrow checker's rulesPauses 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.

        Read it in llama.cpp: three real excerpts that use exactly these ideas (optional, 4 minutes)

        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.

        What each strategy costs, and false friends (3)

        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.

        • "A list is an array." A Python list is an array of pointers; a C++ std::vector<Record> or Rust Vec<Record> holds the records themselves.
        • "A C++ reference keeps the object alive." It does not; it is only another name for memory someone else owns. Python's references are owning; C++'s and Rust's references are borrowing.
        • "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.
        Go deeper: caches, layout (structs of arrays against arrays of structs), SIMD and the memory model, measured, in C++: the machine underneath; RAII, smart pointers and lifetimes in C++: ownership, moves and object lifetimes; lifetime annotations, 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.

        6. Errors and nothingness

        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.

        Nothingness: a key that is not there

        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.

        Errors: a line that does not parse

        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.

        What it costs, and false friends (3)

        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.
        • "Rust's 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.
        Go deeper: Result, Option, ?, 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.

        7. Numbers and text

        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.

        False friends (3)
        • "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.
        • "Integer division rounds down." Only Python's // does; C++, Rust and JavaScript's Math.trunc round towards zero, which differs for negative numbers.
        • "An 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.

        8. Abstraction and polymorphism

        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.

        What it costs, and false friends (2)

        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.

        • "A Rust trait is an abstract base class." There is no inheritance of fields; a trait is closer to a Protocol a type must opt into.
        • "Templates are generics." C++ templates are checked when used with a concrete type (concepts help); Rust generics are checked once, against their bounds, when defined.
        Go deeper: templates, concepts, virtual dispatch and their measured cost in C++: classes, templates and the standard library; traits, generics and 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.

        9. Concurrency

        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.

          Waiting for many slow things: async side by side

          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 asyncioRust tokioJavaScript (Node)
          Calling an async functionBuilds a coroutine; nothing runsBuilds a future; nothing runs until it is polledRuns the body up to the first await
          RuntimeIn the standard libraryA crate you addBuilt in
          Threads polling tasksOne per event loopOne per core by default (multi_thread); idle workers steal tasksOne; libuv's pool of 4 threads does file I/O, DNS lookups, some crypto and zlib
          Fan-outgather, TaskGroupjoin!, JoinSetPromise.all
          Cancellationtask.cancel() raises CancelledError at the current await, so finally runs; re-raise itThe future is dropped, so Drop runs; work half done is lost (cancel safety). Dropping a JoinHandle detaches; abort() cancelsNone 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 insideStalls the loop: every task waitsTies up one worker thread; the others continue. Blocking work goes to spawn_blockingStalls the process: no timer, request or stream moves
          Shared state across tasksNo data races on one loop (the GIL also serialises threads), but tasks interleave at every awaitMust be Send, checked at compile time: a std::sync::Mutex guard held across an .await is refusedNo 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.

          Memory models, what each choice costs, and false friends (3)
          PythonC++RustJavaScript, TypeScript
          Memory modelThe GIL orders bytecode; without it, built-in objects stay consistent but your updates can be lostAtomics with explicit memory orders; everything else must be lockedAtomics and locks; Send and Sync say what may cross threadsAtomics 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.

          • "Threads in Python cannot run in parallel, so other languages' threads are the same." In C++, Rust and free-threaded Python they really run at once, and your racy Python habits become real bugs.
          • "async makes code run in parallel." In Python and JavaScript it interleaves waiting on one thread; tokio is the exception (above).
          • "JavaScript is single-threaded, so it has no concurrency bugs." Two async functions can still interleave at every await, so a read before an await and a write after it can conflict.
          Go deeper: the GIL, asyncio from the event loop up, free-threading and subinterpreters in Python: concurrency, asyncio and the GIL; tokio, cancel safety and an axum service in Rust: async with tokio, services with axum, and CLIs; 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.

          10. Safety and undefined behaviour

          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.

          False friends (2)
          • "If it ran and printed the right thing, it is correct." In C++ a program with undefined behaviour can print the right thing today and the wrong thing after a compiler upgrade. Run tests under AddressSanitizer and UndefinedBehaviorSanitizer.
          • "Rust programs cannot crash." They can panic (out of bounds, unwrap() on None, overflow in debug builds); what they cannot do in safe code is corrupt memory.
          Go deeper: the gallery of undefined behaviour and the sanitizers in C++: the essentials; unsafe, raw pointers and Miri in Rust: lifetimes, smart pointers, threads and unsafe.

          11. Evolution, governance and tooling

          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.

          Who decides, how often, and where each stands now (dated, checked 2026-10-05)
          PythonC++RustTypeScript, JavaScript
          Who decidesThe Steering Council, through PEPs (Python Enhancement Proposals)The ISO committee WG21, through numbered papersRust teams, through RFCs (requests for comments)JavaScript: the TC39 committee, proposals through stages 0 to 4. TypeScript: Microsoft's team
          CadenceOne release a year in October (PEP 602)A standard every three years; compilers adopt features over the following yearsA release every six weeks; an edition every three yearsAn ECMAScript edition each year (TC39 process); TypeScript several releases a year
          Breaking changesDeprecations over several releases; rareAlmost never (C compatibility, decades-old code)Never within an edition; editions opt in per crate and interoperateJavaScript: never ("don't break the web"); TypeScript: new errors in minor releases are accepted
          • Python: 3.15.0 (9 Oct 2026, python.org) is the newest feature line; 3.14 (3.14.8) is in bug fixes
          • C++: C++26 technical work finished on 28 March 2026 (Sutter's trip report); ISO publication not yet confirmed
          • Rust: 1.99.0 (1 Oct 2026); 2024 edition, stable since 1.85.0 (20 Feb 2025) (release notes)
          • TypeScript: TypeScript 7.0, a native port of the compiler to Go, released 8 Jul 2026 (announcement); 7.0.2 used here

          Tooling

          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.

          The tools of each ecosystem, one line each
          • Python: 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.
          • C++: a compiler (clang, GCC, MSVC), a build system (CMake is the common one), a package manager if any (vcpkg, Conan, or none), sanitizers, clang-format and clang-tidy. There is no standard package manager, because compiled C++ libraries must match the compiler and flags they are linked with. Even the default language version differs: Apple clang 14 on this laptop defaults to C++98, recent Clang to C++17, GCC 16 to C++20, MSVC to C++14, so always pass -std=.
          • Rust: 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.
          • TypeScript: a runtime (Node, Bun or Deno), a package manager (npm, pnpm, or Bun's), 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.
          Go deeper: the Toolchain atlas tab lists every tool of the four ecosystems with versions, what each replaces and the commands for the running program. uv, ruff, type checkers, wheels and trusted publishing in Python: typing, uv, packaging and the toolchain; the build (preprocessor, compiler, linker) and CMake in C++: the essentials; Cargo in Rust: the essentials; Node, npm, pnpm, Bun and Deno in JavaScript and TypeScript: the essentials. The Testing and quality page covers testing practice.

          12. Speed and talking to each other

          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.

          How the languages call each other

          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).

          When a rewrite is worth it
          Profile first. If the time is in a loop over Python objects, try a vectorised library (NumPy, polars) or a regex; if it is still too slow and the loop is small and stable, move that loop into a Rust (PyO3) or C++ (nanobind) extension with a batch interface. Rewrite a whole program only when start-up, memory, deployment as a single binary, or concurrency is the problem, not raw loop speed.
          Go deeper: profiling Python, object costs and vectorising in Python: CPython internals and performance; a PyO3 extension step by step, the crossing cost and releasing the GIL in Rust: speeding up Python with PyO3 and maturin. The Benchmark tab has every variant, the per-call crossing cost, start-up, memory and compile times; the methodology of measuring performance is on the Capacity planning and performance page.

          13. Choosing

          Which language for which job

          JobLanguageWhy
          Research, training, evaluation, notebooks, data wranglingPythonThe libraries are there (PyTorch, NumPy, polars, Transformers), and their fast parts are already C++ or Rust underneath.
          Make a hot Python loop fastRust 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 reliableRustA 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 endTypeScript on Node or BunThe 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 kernelsC++ (and C)That is the language those systems are written in; CUDA C++ is C++ with extensions.

          The language pages

          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 and TypeScript: the essentials 19 min, plus 11

          JavaScript runs your code on one thread around an event loop, and TypeScript is a type layer erased before anything runs.

          1. JavaScript: values, objects, functions and modules for Python programmers 28 min, plus 11Looks like Python with braces; the surprises are one number type, a missing value that is undefined rather than an error, this set by the call, and prototype chains.
          2. JavaScript: the event loop, promises and streams 19 min, plus 11One thread that never waits: each callback runs to completion, and every microtask drains before the next macrotask.
          3. TypeScript: the type system, narrowing and runtime validation 30 min, plus 49A checker erased before running: narrowing makes unions safe inside the program, and data from outside needs a runtime schema such as zod.
          4. TypeScript: LLM apps and agents 25 min, plus 25Ordinary server code around one HTTP call: SDK types shape every reply, your loop runs the tools, one zod schema checks the model's JSON.
          Milestone for this step

          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.

          Rust: the essentials 31 min, plus 11

          Every value has one owner and every borrow is checked at compile time, so memory and data-race bugs become compile errors.

          1. Rust: enums, traits, errors and iterators 39 min, plus 18What Python discovers at run time becomes types: enums with exhaustive match, Result in every signature, traits, zero-cost iterators.
          2. Rust: lifetimes, smart pointers, threads and unsafe 21 min, plus 14One rule, many readers or one writer: lifetimes check it, Send and Sync carry it across threads, RefCell and Mutex move it to run time, Miri checks unsafe.
          3. Rust: speeding up Python with PyO3 and maturin 38 min, plus 13An extension pays off only when the whole hot path crosses in one call, borrowing Python's memory and releasing the GIL.
          4. Rust: async with tokio, services with axum, and CLIs 31 min, plus 19A future is a lazy state machine polled by tokio on a few worker threads; axum makes each request a task; the service ships as one file.
          Milestone for this step

          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.

          C++: the essentials 21 min, plus 9

          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.

          1. C++: ownership, moves and object lifetimes 21 min, plus 13Every object has one lifetime ending at a point in the source; RAII and moves let ownership, not a garbage collector, decide when memory is freed.
          2. C++: classes, templates and the standard library 25 min, plus 17Abstractions resolve at compile time unless you ask for run-time dispatch, which costs about 1 to 6 ns a call, measured.
          3. C++: the machine underneath: caches, layout, SIMD and the memory model 33 min, plus 21Once a loop is a handful of instructions, memory sets its speed: cache level, layout and SIMD move it 50 times either way.
          4. C++: reading llama.cpp, one token through the code 37 min, plus 39One token is a ggml graph built once, planned once, and walked by a thread pool through a kernel over weights repacked at load.
          Milestone for this step

          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.

          The seven steps into llama.cpp, with counts from its source (optional)

          Counts at llama.cpp commit , from read/code/llama/excerpts.sh.

          1. C first: structs, fixed-size arrays, pointers and pointer arithmetic, 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]).
          2. Memory and files: stack and heap, alignment and padding, mmap (section 5), and reading a binary format (the GGUF reader is ggml/src/gguf.cpp).
          3. The preprocessor: #if/#ifdef select code per processor and backend (50 such lines in the ARM CPU kernel file alone) and macros such as GGML_RESTRICT.
          4. SIMD intrinsics with a scalar twin: each hot kernel has a portable C loop (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.
          5. Threads: ggml's CPU backend starts its worker threads with pthread_create behind a ggml_thread_create macro; the data-race rules of section 9 apply.
          6. Modern C++ in 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).
          7. The build: CMake with backend options (GGML_CUDA, GGML_METAL, GGML_VULKAN, GGML_HIP, GGML_SYCL, GGML_BLAS), and sanitizers for your own changes.

          Python: the essentials 12 min, plus 1

          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.

          1. Python: the data model and protocols 28 min, plus 21Every operator, loop, with and attribute access is a special-method lookup on the type, with fixed fallbacks.
          2. Python: concurrency, asyncio and the GIL 19 min, plus 10The GIL lets threads overlap waiting but not computing; asyncio swaps threads for one loop that a single blocking call stalls.
          3. Python: CPython internals and performance 23 min, plus 6A bytecode loop over heap objects, so speed comes from moving the loop out of Python, after measuring which loop matters.
          4. Python: typing, uv, packaging and the toolchain 22 min, plus 15Hints are checked by tools, never at run time; packaging is four jobs that uv does as one tool with one lock file.
          Milestone for this step

          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.

          Each axis, traced back to each founding value: the whole design space in one table (optional)
          AxisPython: readabilityC++: zero overhead, C compatibilityRust: safety without a GC, at compile timeTypeScript: erasable types over JavaScript
          How code runsAn interpreter: no compile step to think aboutAhead-of-time machine code, nothing at run timeAhead-of-time machine code, checks done while compilingTypes erased, so JavaScript runs unchanged
          TypesDynamic; hints optional and outside the languageStatic, so the compiler can lay out and inlineStatic and strict: the compiler needs the facts to prove safetyStatic but structural and unsound, to fit existing JavaScript
          b = aShare: names, not boxes, are simplest to readCopy, as C does with structsMove: one owner, so freeing is provableShare, as JavaScript does
          MemoryReference counting: invisible to the readerRAII: deterministic, no collector to pay forOwnership: RAII made checkableJavaScript's garbage collector
          Errors, nothing"Errors should never pass silently": exceptionsExceptions, or no checks at all where they costResult and Option: failure visible in typesJavaScript's exceptions; strict null checks added on top
          Numbers, textBig ints and code points: what a reader expectsMachine integers and bytes: what the hardware doesMachine integers, checked in debug; UTF-8 that cannot be misindexedJavaScript's doubles and UTF-16, kept for compatibility
          AbstractionDuck typing: nothing to declareTemplates: generic code with no run-time costTraits and monomorphisation: generic, fast and checkedStructural interfaces: describe existing JavaScript shapes
          ConcurrencyThe GIL kept the interpreter simple; now optionalThreads with no hidden cost, and no protectionSend and Sync: data races are type errorsOne thread and an event loop, as browsers require
          SafetyEverything checked at run timeUndefined behaviour instead of checksSafe by default; unsafe fenced and searchableMemory-safe JavaScript; types may lie
          EvolutionYearly, with deprecationsNever break old codeEditions: fix mistakes without breaking crates"Don't break the web"; TypeScript moves faster
          Glossary: every term defined on this page, alphabetically (optional)