In Parts 1 and 2 we followed one C program through GCC and LLVM until it became a few machine instructions and returned 19. But a program is more than its instructions. Something has to load it, set it up, call main, clean up when it's done and, in many languages, manage memory while it runs. That something is the runtime.
Every language has one, even C. The difference is how much it does. So, in this post we write the same calculate(5, 7) in five languages and look at what runs around it, from C's tiny startup code to Go's built in scheduler and garbage collector, Python's bytecode interpreter and V8's just in time (JIT) compiler.
Stage 1: The tools and their versions I have used
Everything here runs on an arm64 Mac (Apple Silicon):
Language
Toolchain
C
Homebrew clang 23.1.6 (LLVM)
Rust
rustc (version)
Go
go 1.26.4
Python
CPython (version)
JavaScript
Node.js 26.7.0 (V8)
One note from my side that Runtimes change a lot between versions especially Python and V8. So, what you see may differ on another version.
Stage 2: C has a runtime too
C has no garbage collector, no interpreter and no scheduler so it feels like it has no runtime. But But But, someone has to load the program into memory and call main. We can see who that is by stopping the program at main in a debugger and asking for the backtrace and the chain of function calls that led there:
$CLANG -g -O0 trace.c -o trace_dbglldb ./trace_dbg -o "b main" -o "run" -o "bt" -o "quit"So, here, -g adds debug info, so lldb can show source lines. -O0 keeps main as a real function instead of folding it into mov w0, 19. In lldb and b main sets a breakpoint, run starts the program and bt prints the backtrace.
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 * frame #0: 0x000000010000038c trace_dbg`main at trace.c:20:13 frame #1: 0x00000001a003fe80 dyld`start + 6688Some points here:
1. Only two frames.
frame #0 is our main. frame #1 is the function that called it which means start, inside dyld, macOS's dynamic loader. Well, that's the whole chain. And on macOS the loader calls main directly.
2. Did you see that there's no startup code in our binary.
On Linux, the same backtrace would show _start and __libc_start_main. That's startup code (from files like crt1.o) that the linker copies into every C program. But, modern macOS dropped it. The executable just has a note in its header saying "main is here" and dyld reads that note and jumps straight to main. Our program contains only our own code.
3. What dyld did before calling main
In those 6688 bytes into start before the call, dyld did the setup work like it mapped our program into memory, loaded libSystem (do you guys remember otool -L from Part 1), connected our program to the library functions it uses and ran any initialization code in those libraries.
4. Look at the addresses.
main is at 0x10000038c, inside our program which starts at 0x100000000 (the __PAGEZERO boundary from Part 1). dyld is at 0x1a003fe80 which is much higher up. That's where macOS keeps its shared cache, one big pre linked file holding the system libraries, mapped into every process.
5. Why main + 16 and line 20?
The breakpoint landed 16 bytes into main and not at its first instruction. lldb skips the prologue like the few instructions that set up main's stack frame and stops at the first line of real code: int x = calculate(5, 7);.
6. queue = 'com.apple.main-thread'.
That's a label from Grand Central Dispatch which is Apple's threading library. Every macOS program's first thread gets it like even a C program that never uses GCD. It's a small sign that libSystem is already set up around our code.
So C's runtime is mostly in the OS: dyld loads the program and calls main and libSystem provides the library functions. When main returns 19 the dyld passes it to exit() which runs cleanup like flushing buffered output and hands 19 to the kernel.
Stage 2 (continued): the "main is here" note
otool -l trace_dbg | grep -A4 LC_MAIN cmd LC_MAIN cmdsize 24 entryoff 892 stacksize 0otool -l lists the load commands in the Mach-O header as instructions to dyld about how to load the file. LC_MAIN is the note that says where main is:
entryoff 892 means main starts 892 bytes into the file. 892 in hex is 0x37c. The program is loaded at 0x100000000 so main is at 0x10000037c.
Our breakpoint earlier was at 0x10000038c which is "main + 16". And 0x37c + 16 = 0x38c. The address in the header and the address the debugger stopped at line up exactly.
stacksize 0 means "use the default stack size".
That's how dyld finds main: no _start, just a number in the header.
Stage 2 (continued): what happens after return 19
lldb ./trace_dbg -o "b exit" -o "run" -o "bt" -o "quit"* frame #0: 0x000000019ffeed20 libdyld.dylib`dyld4::LibSystemHelpers::exit(int) const frame #1: 0x00000001a004045c dyld`dyld4::LibSystemHelpersWrapper::exit(int) const + 320 frame #2: 0x00000001a003feb0 dyld`start + 67361. The same start calls exit.
Before here, main was called from start + 6688. Now, exit is called from start + 6736 which is just 48 bytes (12 instructions) later. So, dyld's start is basically:
int result = main();exit(result);2. main is gone from the backtrace.
By the time exit runs, main has already returned so it's no longer on the call stack.
3. dyld passes the call to libSystem through helpers.
The names are C++ (dyld4::LibSystemHelpers::exit) because dyld is written in C++. dyld itself doesn't do the cleanup. These helpers forward the call to libSystem's real exit() which runs atexit handlers, flushes printf buffers and finally asks the kernel to end the process with our exit code.
4. Breakpoint 1: 3 locations
There are three functions named exit in the loaded code and lldb put a breakpoint on all of them. The first one hit is dyld's helper before libSystem's own exit.
5. pacibsp, a security instruction.
The first instruction of the helper is pacibsp. That's ARM's pointer authentication which is like it signs the return address with a secret key so an attacker who overwrites it on the stack can't make the function return somewhere else. Apple's system code uses it everywhere. Our own trace_dbg doesn't since we didn't ask the compiler for it.
6. Where's our 19?
In a C++ method, x0 holds the hidden this pointer so the exit code arrives in the second register, x1. The instruction mov x0, x1 moves it into x0 which is ready to pass to the real exit.
So, C's whole runtime on macOS: dyld reads LC_MAIN, calls main then takes the return value and calls exit. libSystem does the cleanup and the kernel ends the process. Nothing extra is compiled into our program.
Stage 3: Rust, a thin runtime of its own
Rust compiles to machine code just like C with no garbage collector or interpreter. But it adds a small runtime layer of its own around main. Here's the same program in Rust:
fn calculate(a: i32, b: i32) -> i32 { let sum = a + b; let mut result = sum * 2; if result > 20 { result -= 5; } result}fn main() { let x = calculate(5, 7); std::process::exit(x);}Rust's main can't return a plain number like C's, so we use std::process::exit(x) to hand 19 back to the OS.
rustc -g -C opt-level=0 trace.rs -o trace_rs./trace_rs; echo $?lldb ./trace_rs -o "b trace::main" -o "run" -o "bt" -o "quit"frame #0: trace::main trace.rs:11frame #1: FnOnce::call_once function.rs:250frame #2: std::sys::backtrace::__rust_begin_short_backtraceframe #3: std::rt::lang_start::{closure#0}frame #4–11: catch_unwind / closures [opt] [inlined]frame #12: std::rt::lang_start_internal [opt]frame #13: std::rt::lang_start(main, argc=1, argv, sigpipe)frame #14: main + 36frame #15: dyld`start + 6688Guys read it from the bottom up in the order things happen:
1. dyld calls a function called main but it isn't ours.
frame #14 is a plain C-style main that the Rust compiler generated. It's the function LC_MAIN points to because dyld only knows how to call a C main. So, our Rust main is called trace::main (frame #0). The generated main just passes control to the Rust runtime.
2. lang_start and lang_start_internal: Rust's startup code.
This is the Rust runtime. Before calling our code it does setup work that C doesn't:
Saves argc and argv (we can see
argc=1in frame #13) sostd::env::args()works later.Handles SIGPIPE. The
sigpipeargument controls this. Like by default, Rust ignores the SIGPIPE signal so writing to a closed pipe returns an error instead of killing the program the way it would in C.Names the main thread. Look at the top of the backtrace here as
thread #1, name = 'main'. In the C program the thread had no name. Rust's runtime gave it one and that's the name you see in panic messages like "thread 'main' panicked".
3. catch_unwind: catching panics before they escape.
here, frames 4 to 11 are all catch_unwind. if our code panics, Rust unwinds the stack. But, unwinding must never run into dyld's C code which knows nothing about Rust panics. So, the runtime wraps main in catch_unwind catches any panic at the border and prints the message and exits with an error code. C has no equivalent since it has no panics.
4. __rust_begin_short_backtrace: a marker.
This function does nothing except call our main. It's like a bookmark. When a Rust program panics with RUST_BACKTRACE=1 then the printed backtrace is cut off at this function so you see your own frames and not all the runtime frames we are looking at now.
5. [opt] and [inlined]: two kinds of code in one binary.
Our program was compiled with opt-level=0 but frames 4 to 12 say [opt]. They come from Rust's standard library which ships already compiled with optimizations. Most of those functions were inlined into lang_start_internal and lldb rebuilds them from debug info. The addresses show the split as see here now like our code and the generic parts compiled for our program sit around 0x1000009xx while the precompiled std code sits at 0x100018xxx.
6. The binary is 27× bigger.
trace_dbg 17,192 bytes (C)trace_rs 469,656 bytes (Rust)C's runtime lives in libSystem which is shared by every program on the Mac. Rust statically links its standard library as the parts we use (startup, panic handling, printing, backtraces) are copied into our binary. Rust still uses libSystem underneath but carries its own layer on top. (Debug info and -O0 add to the size too so a fair comparison would use optimized and stripped builds.)
7. Btw, a side note on std::process::exit.
It calls libSystem's exit() immediately which is the same function C used. That means main never returns so lang_start never gets its result and any Rust values still alive are never cleaned up (their destructors don't run). For an i32, that doesn't matter.
So: Rust's runtime is small and compiled into the program. It's mostly about startup setup and making sure panics are handled safely. There's still no garbage collector and no scheduler. Those show up in the next language.
A fair size comparison
Debug builds aren't a fair comparison so here are both programs optimized and with symbols stripped:
$CLANG -O2 trace.c -o trace_c_rel && strip trace_c_relrustc -C opt-level=2 -C strip=symbols trace.rs -o trace_rs_rells -l trace_c_rel trace_rs_reltrace_c_rel 16,840 bytes (C)trace_rs_rel 342,304 bytes (Rust)1. The C binary barely shrank (17,192 --> 16,840).
Our C code is only a few instructions so almost all of those 16 KB is structure like the Mach-O header, load commands and padding. On Apple Silicon the memory pages are 16 KB and the file's sections are aligned to page boundaries so even a tiny program ends up around 16 KB.
2. Rust dropped by about 127 KB (469,656 --> 342,304).
That was mostly debug info. What's left is about 20 times the C binary which is the part of Rust's standard library compiled into the program. the startup code from Stage 3, plus the panic machinery. even though our program never panics the code that would print a panic message (with text formatting and backtrace support) has to be included because the compiler can't prove a panic will never happen.
3. Can Rust be made smaller?
rustc -C opt-level=z -C panic=abort -C strip=symbols trace.rs -o trace_rs_smalltrace_rs_small 342,080 bytesthis is only 224 bytes smaller. Flags like opt-level=z (optimize for size) and panic=abort (crash instead of unwinding) only affect the code rustc compiles right now which is our tiny trace.rs. Rust's standard library ships precompiled with unwinding support built in and that's where almost all of the 340 KB lives. To really shrink it we would have to rebuild the standard library itself with those settings like with aa nightly only feature or leave it out completely with #![no_std] and write our own startup code.
That's a good way to see where a runtime lives as Rust's isn't something you can switch off with a flag. It's a prebuilt library you link in as all of it or none.
Stage 4: Go, a full runtime in every binary
Rust's runtime set things up and then stepped aside. Go's runtime stays which means it manages memory with a garbage collector and runs goroutines with its own scheduler for the whole life of the program. Same program in Go:
package mainimport "os"func calculate(a, b int) int { sum := a + b result := sum * 2 if result > 20 { result -= 5 } return result}func main() { x := calculate(5, 7) os.Exit(x)}go build -gcflags="all=-N -l" -o ../trace_go main.go./trace_go; echo $?lldb ./trace_go -o "b main.main" -o "run" -o "bt" -o "thread list" -o "quit"-N turns off optimizations and -l turns off inlining. the Go version of -O0. It returns 19 like the others.
1. The binary is 2.1 MB.
trace_c_rel 16,840 bytes (C)trace_rs 469,656 bytes (Rust, debug)trace_go 2,120,466 bytes (Go, debug)Every Go program carries the complete Go runtime which means the garbage collector, the goroutine scheduler, the code that grows stacks and tables the runtime uses to understand its own stack frames. A program that only adds two numbers pays for all of it.
2. The backtrace stops after two frames.
frame #0: trace_go`main.mainframe #1: trace_go`runtime.main + 556In C, main was called by dyld. In Rust, there were 16 frames but they still reached all the way down to dyld. In Go the chain ends at runtime.main with no dyld underneath.
Well, that's because main.main (our main) doesn't run on the thread's original stack. During startup the Go runtime creates a goroutine with its own small, separate stack and runs runtime.main on that goroutine. runtime.main finishes setting up (it starts the garbage collector's background work, runs package init functions and so on) then calls our main.main. Since the goroutine's stack was created fresh so there's nothing older on it to show. Even the program's main function is a goroutine like any other scheduled by the runtime.
3. Every function starts by checking its stack.
The breakpoint landed on main's first instruction and now let's look at what it is:
ldr x16, [x28, #0x10]cmp sp, x16b.ls 0x1000a0868On ARM64, Go keeps a pointer to the current goroutine in register x28. The first line loads that goroutine's "stack guard" which is the lowest safe point of its stack. The next two compare it with the stack pointer and if there isn't enough room, jump to code that grows the stack.
Goroutine stacks start tiny which is just a few kilobytes which is why a Go program can run hundreds of thousands of goroutines at once. The cost is this check at the start of (almost) every function. C and Rust don't have it because their threads get one big fixed stack from the OS.
4. Five threads before main even starts.
* thread #1: main.main thread #2: libsystem_kernel.dylib`__semwait_signal + 8 thread #3: libsystem_kernel.dylib`__psynch_cvwait + 8 thread #4: libsystem_kernel.dylib`__psynch_cvwait + 8 thread #5: libsystem_kernel.dylib`__psynch_cvwait + 8Our C and Rust programs had one thread. Go has five and our code started none of them. Thread 1 is running our main. The other four are the runtime's all asleep, waiting inside the kernel like see here:
__semwait_signalis a timed sleep. This is most likely sysmon which is a runtime thread that wakes up regularly to watch the program. like for example to stop a goroutine that has run too long.__psynch_cvwaitis waiting on a condition variable. These are worker threads as parked until the scheduler has goroutines for them to run.
So: Go's runtime isn't just startup code. It's a small operating system living inside the program with its own threads, scheduler, stacks and garbage collector, running alongside our code the whole time.
Stage 4 (continued): what the other threads are doing
thread #2 libsystem_kernel.dylib`__semwait_signal libsystem_c.dylib`nanosleep libsystem_c.dylib`usleep trace_go`runtime.usleep_trampoline.abi0thread #3, #4, #5 libsystem_kernel.dylib`__psynch_cvwait libsystem_pthread.dylib`_pthread_cond_wait trace_go`runtime.pthread_cond_wait_trampoline.abi0 trace_go`runtime.asmcgocall.abi01. Thread 2 is sleeping in a loop.
The Go runtime called usleep (sleep for some microseconds) which went through libSystem's nanosleep down to the kernel. That matches sysmon which is the runtime's monitor thread means it sleeps a little, wakes up to check the program for example, a goroutine running too long or memory to give back and sleeps again. lldb can't follow the stack back into Go's own frames past the trampoline so we don't see the function name itself but the sleep pattern is sysmon's.
2. Threads 3 to 5 are parked workers.
They are waiting on a condition variable (pthread_cond_wait) which is a standard "sleep until someone wakes me" call. These are runtime worker threads with no goroutines to run yet. When the program has work for them then the scheduler wakes one up.
3. Go calls libSystem through "trampolines".
did you notice that usleep_trampoline and pthread_cond_wait_trampoline. On macOS Apple only supports talking to the kernel through libSystem and not with raw system calls so even Go has to call libSystem's C functions. But C code can't run on a tiny goroutine stack which might be too small. So asmcgocall first switches to a normal sized system stack and the trampoline then calls the C function there. Every time Go talks to the OS on macOS it goes through this bridge.
Stage 4 (continued): the real entry point
nm trace_go | grep -i rt000000001000780a0 t __rt0_arm64_darwin00000001000755c0 t _runtime.rt0_go.abi00000000100047160 t _runtime.mstart0_rt0_arm64_darwin is where Go programs really start as the function dyld calls instead of a C main (the extra underscore at the front is macOS's naming convention). "rt0" means "runtime, step zero". The full chain which our backtrace couldn't show is here see:
dyld calls
_rt0_arm64_darwinwhich jumps to
runtime.rt0_gothe core setup like it creates the first goroutine structure and the first thread structure which saves argc/argv checks the CPU and sets up the scheduler and memory allocatorit then creates a goroutine for
runtime.mainand starts the scheduler (runtime.mstart0)the scheduler picks that goroutine to run and
runtime.mainfinally calls ourmain.main
That's why our backtrace ended at runtime.main. Steps 1 to 3 happened on a different stack before our goroutine existed. The lowercase t means these are local symbols used only inside the binary
The fair size comparison, all three
go build -ldflags="-s -w" -o trace_go_rel gotrace/main.gols -l trace_c_rel trace_rs_rel trace_go_reltrace_c_rel 16,840 bytes (C)trace_rs_rel 342,304 bytes (Rust)trace_go_rel 1,471,218 bytes (Go)Even stripped Go is about 1.4 MB as roughly 87 times the C binary and 4 times Rust. Stripping can't remove everything because the Go runtime needs some of that information while the program runs. It keeps tables describing every function's stack frame so it can grow goroutine stacks (the check from point 3) find pointers on the stack for the garbage collector and print stack traces on panic. In C and Rust that kind of information is only for debuggers so it can go. In Go the runtime itself uses it.
Stage 5: Python, no machine code at all
C, Rust and Go all turned our code into ARM instructions ahead of time. Python doesn't. It compiles our code to bytecode, instructions for an imaginary machine and a program written in C (the CPython interpreter) reads and runs those instructions one by one. dis lets us look at that bytecode like objdump -d did in Part 1:
$PY trace.py; echo $?$PY -m dis trace.pyIt prints 19. Now here's the bytecode for calculate:
2 LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (a, b) BINARY_OP 0 (+) STORE_FAST 2 (sum) 3 LOAD_FAST_BORROW 2 (sum) LOAD_SMALL_INT 2 BINARY_OP 5 (*) STORE_FAST 3 (result) 4 LOAD_FAST_BORROW 3 (result) LOAD_SMALL_INT 20 COMPARE_OP 148 (bool(>)) POP_JUMP_IF_FALSE 10 (to L1) NOT_TAKEN 5 LOAD_FAST_BORROW 3 (result) LOAD_SMALL_INT 5 BINARY_OP 23 (-=) STORE_FAST 3 (result) 6 L1: LOAD_FAST_BORROW 3 (result) RETURN_VALUE1. It's a stack machine, not a register machine.
ARM did add w0, w0, w1 like naming registers directly. Python's VM has no registers. So, instructions push values onto a stack and pop them off. sum = a + b becomes this here as push a, push b, BINARY_OP + pops both and pushes the result, STORE_FAST pops it into sum. Bytecode is simple to generate and simple to interpret but it takes more steps for the same work.
2. Nothing was optimized away.
GCC and Clang turned calculate(5, 7) into 19. Python's compiler doesn't and it can't. In Python calculate is just a variable holding a function and some other code could replace it before it's called. So the compiler can't assume what the call will do. Guys look at the module code at the top as it really calls the function at runtime with LOAD_SMALL_INT 5, LOAD_SMALL_INT 7, CALL 2.
3. * 2 is still a multiply.
No shift unlike every compiler so far. The compiler doesn't know sum will be an integer. It could be a float or a string ("ab" * 2 is "abab") or any object with its own *. BINARY_OP is a generic operation and at runtime it checks the types of its inputs and then decides what to do. This type check on every operation is a big part of why Python is slower than compiled languages.
4. The if is still a jump.POP_JUMP_IF_FALSE is a real branch with no csel trick. The NOT_TAKEN after it does nothing when the code runs. It's a marker that lets tools like debuggers and coverage tools see which way each branch went. bool(>) in the COMPARE_OP means the comparison produces a true/false directly for the jump.
5. Small speed tricks are already built in.
LOAD_FAST_BORROW_LOAD_FAST_BORROWis a superinstruction: as here two loads (a and b) combined into one instruction so the interpreter does one dispatch instead of two.BORROWmeans the value is loaded without updating its reference count. Python tracks how many references each object has for memory management and when the interpreter can prove a value stays alive it skips that bookkeeping.LOAD_SMALL_INTputs small numbers like 2, 5 and 20 directly into the instruction instead of looking them up in a constants table.
6. Even def runs at runtime.
At the top of the module defining the function is itself an instruction like MAKE_FUNCTION creates a function object and STORE_NAME saves it under the name calculate. In C functions exist in the binary before the program starts. But, in Python they are created while the program runs. import sys is a runtime operation too (IMPORT_NAME).
7. sys.exit(19) doesn't exit directly.
It raises an exception (SystemExit). The interpreter catches it at the top level then runs cleanup and only then exits with code 19. That's very different from C where exit() ends the process at once.
So where's the machine code? It's in the python3 program itself. The interpreter's main loop is written in C and each bytecode instruction is a section of C code inside it. When BINARY_OP runs then the CPU is executing the interpreter's "handle a binary operation" code and not code generated for our program. Our program is data that the interpreter reads.
Stage 5 (continued): Python optimizes itself while running
import dis, runpyns = runpy.run_path("trace.py")calculate = ns["calculate"]for _ in range(1000): calculate(5, 7)dis.dis(calculate, adaptive=True)We load calculate and then call it 1000 times then look at its bytecode again. adaptive=True shows the bytecode as it is now in memory and after running.
Before warm-up After 1000 callsRESUME → RESUME_CHECKBINARY_OP (+) → BINARY_OP_ADD_INTBINARY_OP (*) → BINARY_OP_MULTIPLY_INTCOMPARE_OP (>) → COMPARE_OP_INTBINARY_OP (-=) → BINARY_OP_SUBTRACT_INT1. The generic instructions became integer instructions.
well remember the problem from Stage 5 the one where BINARY_OP doesn't know if it's adding ints, floats or strings so it checks every time. While our loop ran the interpreter noticed that this + only ever saw integers and rewrote that instruction in place as BINARY_OP_ADD_INT. This is called the specializing adaptive interpreter added in Python 3.11 and described in PEP 659.
2. Specialized doesn't mean blind.BINARY_OP_ADD_INT still checks that both inputs really are ints. But that's one quick check followed by a direct integer add instead of the full "what types are these and how do I add them?" lookup. and if a float ever shows up then the check fails then the instruction falls back to the generic version and Python can specialize it again later. The program always stays correct since only the speed changes.
3. The loads and jumps stayed the same.LOAD_FAST_BORROW, STORE_FAST, POP_JUMP_IF_FALSE and RETURN_VALUE didn't change. They do the same work whatever the types are so there's nothing to specialize. RESUME became RESUME_CHECK, a lighter version that only checks if the interpreter needs to stop for something like a signal.
4. It's still bytecode.
This is the key limit. The instructions got smarter but the interpreter still reads them one at a time and the multiply is still a multiply and not a shift. No machine code was generated for our function. The rewritten bytecode only exists in memory and it's gone when the program ends. Well, Python has an experimental JIT that goes further but it's off by default.
Compared with GCC and Clang: they knew the types at compile time (int a, int b) so they could specialize everything before the program ran. Python doesn't know the types until it sees them so it specializes while running like based on what actually happens. That's the core idea behind every fast dynamic language runtime and the next one takes it all the way to machine code.
Stage 6: JavaScript (Node/V8), compiling while running
Python improves its bytecode while the program runs. V8 goes further like when code gets hot, it compiles it to real machine code during the run. This is a JIT (just in time) compiler. Same program in JavaScript:
function calculate(a, b) { const sum = a + b; let result = sum * 2; if (result > 20) { result -= 5; } return result;}let x = 0;for (let i = 0; i < 100000; i++) { x = calculate(5, 7);}process.exit(x);The loop calls calculate 100,000 times to make it "hot". Like Python here V8 only spends effort optimizing code that runs a lot. It exits with 19.
Part A: V8's bytecode
node --print-bytecode --print-bytecode-filter=calculate trace.jsLdar a1 ; acc = bAdd a0, FBV[0] ; acc = a + accStar0 ; r0 = acc (sum)MulSmi [2], FBV[1] ; acc = acc * 2Star1 ; r1 = acc (result)LdaSmi [20] ; acc = 20TestGreaterThan r1, ... ; acc = r1 > accJumpIfFalse [8]Ldar r1 ; acc = resultSubSmi [5], FBV[2] ; acc = acc - 5Star1 ; result = accLdar r1ReturnV8's interpreter is called Ignition. now let's compare it with Python's bytecode:
1. A different kind of virtual machine.
Python's VM pushes and pops values on a stack. Ignition uses registers plus an accumulator which means most instructions work on one special register the accumulator (acc) and Star/Ldar move values between it and numbered registers (r0, r1). Our local variables became registers like the sum is r0 and result is r1. The parameters are a0 (a) and a1 (b). It's a different design from Python's but the same basic idea which is instructions for a virtual machine and not for the CPU.
2. Smi: V8's fast integers.MulSmi [2] and SubSmi [5] mean "multiply/subtract by a small integer". V8 stores small integers directly inside the value itself, instead of allocating an object for each number. So operations on them are cheap.
3. FBV[0]: where V8 records what it has seen.Add a0, FBV[0] has an extra operand pointing to a slot in the function's feedback vector. Every time the Add runs then V8 records which types it saw there like say "always small integers" for example. This is the same idea as Python's specialization but instead of rewriting the instruction here V8 keeps the notes on the side for its optimizing compilers to use later.
4. The numbers on the left.41 S> and 43 E> are character positions in trace.js where each Statement or Expression starts. They let V8 point error messages and stack traces back to the source just like "trace.c":9:9 in GCC's RTL.
Part B: watching the JIT work
node --trace-opt --trace-deopt trace.js[marking calculate for optimization to MAGLEV, ConcurrencyMode::kConcurrent, reason: hot and stable][compiling method calculate (target MAGLEV), mode: ConcurrencyMode::kConcurrent][marking <JSFunction> for optimization to MAGLEV ... reason: hot and stable][compiling method <JSFunction> (target MAGLEV) OSR ...][completed compiling calculate (target MAGLEV) - took 0.001, 0.180, 0.000 ms][completed compiling <JSFunction> (target MAGLEV) OSR - took 0.000, 0.179, 0.001 ms][compiling method <JSFunction> (target TURBOFAN_JS) OSR ...][bailout (kind: deopt-eager, reason: Insufficient type feedback for generic global access): begin. deoptimizing <JSFunction> ...]Now I want all to read this as a story:
5. calculate got hot so V8 compiled it.
After enough calls the V8 marked calculate for optimization liek see here as "hot and stable". Hot means it runs a lot and stable means the feedback vector keeps seeing the same types. It was compiled with Maglev which is V8's mid level optimizing compiler in about 0.18 milliseconds. From then on it calls to calculate run as real ARM machine code instead of being interpreted.
6. It compiled on another thread.ConcurrencyMode::kConcurrent means the compiling happened on a background thread. The main thread kept running the loop in the interpreter and when the machine code was ready then V8 switched to it. The program never paused to compile.
7. The loop itself got compiled too, in the middle of running.
The unnamed <JSFunction> is our top level script so the code with the for loop. It also got hot but it runs only once so V8 can't wait for "the next call" to use faster code. Instead, it used OSR (On Stack Replacement) which means it compiled the loop and switched to the machine code version while the loop was still running and partway through its 100,000 iterations. V8 then started compiling it again with TurboFan which is the its top level and most aggressive optimizing compiler.
8. Then it threw that code away (a deoptimization).
The last line is a deopt like V8 dropped the optimized code for the top level script and went back to the interpreter. The reason for that is "Insufficient type feedback for generic global access". The optimized code was built from what V8 had seen during the loop and a global variable was accessed that it had never seen before. That's most likely process in process.exit(x) which only runs once after the loop. Since V8 had no information about it so it gave up on the optimized code and let the interpreter handle that line.
This is the deal a JIT makes: it optimizes based on guesses from what it has seen so far and when a guess fails it falls back safely and keeps going. Python's specialized instructions do the same thing on a smaller scale.
9. V8 has several tiers.
Our function went from the Ignition interpreter to the Maglev compiler and the loop was on its way to TurboFan. (V8 also has a fast baseline compiler called Sparkplug between Ignition and Maglev which --trace-opt doesn't report here) Each tier compiles more slowly but produces faster code so V8 only moves code up a tier when it's proven worth it.
Compared with everything so far: GCC and Clang do all their optimizing before the program runs with full knowledge of the types. V8 starts with nothing, watches the program and optimizes while running based on what it observed. Fun fact - It can even beat ahead of time compilers sometimes because it knows how the code is actually used.
Stage 7: The cost of each runtime
Our program does almost nothing like it does add, multiply, compare and return 19. So measuring how long it takes really measures how long each runtime takes to start up and shut down. hyperfine runs each program hundreds of times:
hyperfine -N -i --warmup 3 ./trace_c_rel ./trace_rs_rel ./trace_go_rel "$PY trace.py" "node trace.js" Fastest run Peak memoryC 2.2 ms 1.6 MiBRust 2.3 ms 1.7 MiBGo 2.9 ms 4.0 MiBPython 3.15 21.7 ms 13.0 MiBNode 26 (V8) 45.3 ms 45.6 MiB(-i ignores the exit code 19 which hyperfine would otherwise treat as a failure. -N runs each program directly without a shell in between.)
1. C and Rust are tied.
About 2 ms each. Most of that isn't our program at all like it's macOS creating a new process, dyld loading it and connecting libSystem then tearing it all down. Rust's extra startup (saving args and the panic setup) is too small to measure here. The averages look different only because of a few slow outlier runs which is why we compare the fastest run.
2. Go costs a little more.
About 0.7 ms more and 2.5 times the memory. That's the runtime from Stage 4 starting up like setting up the scheduler and the memory allocator and starting the extra threads we saw in lldb. Every one of those threads needs its own stack and the garbage collector reserves memory up front.
3. Python is about 10 times slower to start before our code even runs.
22 ms and 13 MiB. Most of that is the interpreter starting like loading itself, creating its built in objects and importing the standard modules it needs at startup. And, compiling our 11 line file to bytecode is a tiny part of it.
4. Node is the heaviest.
45 ms and 46 MiB. V8 has to set up a whole JavaScript engine (a heap with a garbage collector, the Ignition interpreter and the compilers) before running a single line. Our Node test also runs the 100,000 call loop but with the JIT that takes well under a millisecond so it's not what makes Node slow here.
This is the tradeoff in one table covered. The more a runtime does for you like memory management, scheduling, running code without compiling ahead of time and optimizing while it runs then the more it costs to start. For a server that runs for days, 45 ms once doesn't matter and the JIT can make long running code very fast. For a command line tool you run hundreds of times a day it's the difference between instant and noticeably slow. That's one reason tools like ripgrep and esbuild are written in compiled languages.
The whole journey in one table
C | Rust | Go | Python | JavaScript (V8) | |
|---|---|---|---|---|---|
Runs as | machine code | machine code | machine code | bytecode, interpreted | bytecode, then JIT machine code |
Who calls | dyld | dyld -> Rust | dyld -> | interpreter | V8 engine |
Memory management | manual | ownership (compile time) | garbage collector | reference counting + GC | garbage collector |
Extra threads at start | 0 | 0 | 4 | – | – |
Optimizes | before running | before running | before running | while running (specializes bytecode) | while running (compiles to machine code) |
Stripped binary size | 16 KB | 342 KB | 1.4 MB | – | – |
Startup (fastest) | 2.2 ms | 2.3 ms | 2.9 ms | 21.7 ms | 45.3 ms |
So, what actually runs your code?#
Always something more than your code. Even C has a runtime like dyld loads the program, calls main, takes its return value and calls exit. The difference between languages is how much more the runtime takes on.
Rust adds a thin layer to handle panics safely and compiles it into every binary. Go brings a small operating system of its own, with threads, a scheduler, growable stacks and a garbage collector running alongside our code the whole time. Python skips machine code entirely and interprets bytecode rewriting its own instructions as it learns your types. V8 goes the furthest as it watches our program run, compiles the hot parts to machine code on a background thread and safely throws that code away when its guesses turn out wrong.
In Parts 1 and 2 we watched compilers turn calculate(5, 7) into mov w0, 19 before the program ever ran. A JIT does the same kind of work just later while the program runs with information an ahead of time compiler never has. Compilers and runtimes aren't really separate topics. They arre the same job split differently in time.
A note on scope: everything here is on an arm64 Mac with the versions listed at the top. Runtimes change quickly especially Python's and V8's and startup times depend a lot on the machine.
Enjoyed this? Get the next post by email.
Get new posts on compilers and systems in your inbox. No spam, unsubscribe anytime.

Comments