Parameters & SIMD
22 steps in 5 sets of Mojo.
Mojo splits every function into two halves: what the compiler can settle and what the machine has to do. Square brackets carry compile-time parameters, so a size or a type is nailed down before the program starts and the generated code has nothing left to check. SIMD is the other half — a vector type that maps onto a real hardware register, where one instruction adds four lanes at once.
Together they are the reason Mojo exists. This tour walks from `comptime` bindings and parametric structs through masks, casts, and reductions, then down to raw pointers and spans, and finishes with the mandelbrot render that made the language famous.
Compile-time Mojo
- Compile-time constants
comptimebindings are folded before the program runs - zero cost at runtime. - Parametric functionsSquare brackets take compile-time parameters; parentheses take runtime arguments.
- Parametric structsA struct parameter fixes a size at compile time, so no capacity check survives.
- Compile-time expressionsAn ordinary function runs at compile time when its result feeds a
comptimebinding. - Compile-time branching
comptime ifandcomptime forare resolved by the compiler, leaving no branch behind.
SIMD
- SIMD vectors
SIMDis a fixed-width vector that maps straight onto a hardware register. - SIMD arithmeticArithmetic on
SIMDhits every lane at once, in a single instruction. - SIMD reductionsReductions collapse a whole vector down to one scalar in log-depth steps.
- SIMD masksComparisons yield a lanewise mask, and
selectuses it to blend two vectors. - Casting SIMD lanes
castconverts every lane to anotherDTypewithout leaving the vector. - Splatting a scalarHanding a
SIMDconstructor one value broadcasts it across every lane.
Numbers & time
- Math functions
std.mathcovers the usual scalar functions and applies them lanewise toSIMD. - Random numbersSeeding first makes a random run reproducible, which is what benchmarks need.
- Timing a loop
perf_counter_nsbrackets a block of work to measure how long it really took. - Bitwise operationsShifts and masks are how flags, hashes, and packed formats get handled.
- Float32 against Float64Narrower floats are faster and smaller, but they carry fewer digits.
Memory
- Unsafe pointers
allochands back raw memory that you index directly and must free yourself. - Pointer arithmeticAdding to a pointer moves it by whole elements, never by bytes.
- List capacityA
Listdoubles its buffer as it grows, which is what makes appends cheap. - Span viewsA
Spanborrows a window into a list without copying any of it.
Encore
- Mandelbrot in ASCIIThe demo Mojo is known for - escape-time rendering, four columns at a time.
- Timed prime sieveA sieve of Eratosthenes with a nanosecond timer wrapped around it.