Skip to content

Mojo Performance Tips

Mojo code is compiled to machine code before it runs, so a plain loop doesn’t pay the per-step costs a Python loop does. Most of the time you don’t need tricks. When something is too slow, the fix is usually one of a few everyday habits, not SIMD wizardry. This page collects them, each with a small example, and ends with how to find out where a program spends its time. Every timing here was measured on our test machine (a 4-core Linux VM) and will be different on yours; run the examples to get your own numbers.

Before you change anything for speed, time it (the Mojo Benchmarking lesson shows how). Then change one thing and time it again. Two reasons:

  • Your guess about the slow part is often wrong. A program that “obviously” spends its time in the math may really spend it reading a file.
  • Some changes that sound faster aren’t, on your data, on your CPU. The only way to know is the measurement.

Keep the slow version around until the fast one gives the same results.

In Mojo, passing a value to a function doesn’t copy it. By default the function gets a read-only reference to your value (the Mojo manual’s page on ownership explains all the options), which costs nothing, whatever its size. (In Python, all arguments are references too, so this part will feel natural.)

A copy only happens when a function asks to own its argument with var. For types like List, Mojo then refuses to copy quietly:

def total(var xs: List[Int]) -> Int:
var s = 0
for x in xs:
s += x
return s
def main():
var data: List[Int] = [1, 2, 3]
print(total(data))
hello.mojo:9:17: error: value of type 'List[Int]' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable'
print(total(data))
^~~~
hello.mojo:9:17: note: consider transferring the value with '^'
hello.mojo:9:17: note: you can copy it explicitly with '.copy()'
mojo: error: failed to parse the provided Mojo source module

That error is a performance feature: every copy of a big value is visible in your code. You have three choices, from cheapest to most expensive:

You write What happens Cost
def total(xs: List[Int]) The function reads your list in place Nothing extra
total(data^) The list is moved in; data can’t be used afterwards Nothing extra
total(data.copy()) A full copy is made Proportional to the list’s size

Here’s what that last row costs for a list of a million Ints:

from std.benchmark import run, keep, Unit
def total(xs: List[Int]) -> Int:
var s = 0
for x in xs:
s += x
return s
def total_owned(var xs: List[Int]) -> Int:
var s = 0
for x in xs:
s += x
return s
def main() raises:
var data = List[Int](capacity=1_000_000)
for i in range(1_000_000):
data.append(i)
def by_ref() {imm data}:
keep(total(data))
def with_copy() {imm data}:
keep(total_owned(data.copy()))
print("read in place: ", round(run(by_ref, max_runtime_secs=1.0).mean(Unit.ms), 3), "ms")
print("copy, then read:", round(run(with_copy, max_runtime_secs=1.0).mean(Unit.ms), 3), "ms")

You’ll see something like this (one run on our test machine):

read in place: 0.497 ms
copy, then read: 1.148 ms

Over three runs, copying first took about twice as long as reading in place. So: leave arguments as the default unless the function really needs to keep the value, and when it does, move with ^ if you’re done with it. The Mojo Argument Conventions and Mojo Moving Values lessons cover the details.

Reserve list capacity when you know the size

Section titled “Reserve list capacity when you know the size”

A List grows as you append. When it runs out of room, it allocates a bigger block and moves everything over. If you know roughly how many items are coming, say so up front with capacity=:

from std.benchmark import run, keep, Unit
comptime N = 1_000_000
def grow() -> List[Int]:
var xs = List[Int]()
for i in range(N):
xs.append(i)
return xs^
def reserve() -> List[Int]:
var xs = List[Int](capacity=N)
for i in range(N):
xs.append(i)
return xs^
def main() raises:
def a():
keep(len(grow()))
def b():
keep(len(reserve()))
print("no capacity:", round(run(a, max_runtime_secs=1.0).mean(Unit.ms), 3), "ms")
print("capacity=N: ", round(run(b, max_runtime_secs=1.0).mean(Unit.ms), 3), "ms")

You’ll see something like this (one run on our test machine):

no capacity: 1.151 ms
capacity=N: 0.382 ms

Across three runs, reserving was roughly 2.5 to 3 times faster here. capacity= doesn’t change what’s in the list (it’s still empty until you append); it only sets aside the room. If you need the slots filled right away, List[Int](length=N, fill=0) makes them all at once.

Your choice of number type matters for speed as well as correctness. A few habits:

  • Use Int for counts and indexes. It’s what len(), range() and list indexing use, so you avoid conversions.
  • Use Float32 when 7 digits are enough. Twice as many Float32 as Float64 values fit into one SIMD register (on our test machine: 16 against 8), so vectorized math can do twice the work per step.
  • Use small integer types (UInt8, Int16) for data that really is small, like pixels. More lanes again, and less memory to read. But they wrap around silently, so do the math in a wider type when results can grow, as in the Mojo DType practice.
  • Don’t mix types in a hot loop. Mojo won’t mix DTypes for you, so mixing means a .cast on every step. Convert once, outside the loop.

Values you write with comptime are known while compiling. The compiler can then build them into the code, unroll short loops and pick SIMD widths:

from std.sys import simd_width_of
comptime CHANNELS = 4
comptime WIDTH = simd_width_of[DType.float32]()
def main():
var pixel = SIMD[DType.float32, CHANNELS](0.2, 0.4, 0.6, 1.0)
print(pixel * 255)
print(WIDTH > 0)

Output:

[51.0, 102.0, 153.0, 255.0]
True

A SIMD width must be a compile-time value anyway, so things like CHANNELS and WIDTH have to be comptime. For sizes that really are fixed (a 4-channel pixel, a 3x3 filter), making them comptime instead of a normal variable gives the compiler more to work with. Don’t force it for values that come from the user or a file.

When a loop really is the bottleneck, try these in order, measuring after each step:

  1. A better approach. Doing less work beats doing the same work faster. A Dict lookup instead of searching a list, or stopping a loop early, can matter more than anything below.
  2. The habits above. No copies, reserved capacity, the right types.
  3. SIMD with vectorize for math over long lists of numbers. On our test machine a vectorized sum was about 4 to 5 times faster than the plain loop. See Mojo Vectorize.
  4. More cores with parallelize for big, independent chunks of work. On our 4-core VM that gave about 1.5 to 3 times, and made small jobs slower. See Mojo Parallelize.

Each step makes the code harder to read, so stop as soon as it’s fast enough.

Timing tells you how long. A profiler tells you where: which lines or functions use the most time. The mojo command has no profiler of its own, but because mojo build makes a normal executable, the usual system tools work on it. Build with -g so the tool can map machine code back to your source lines.

Here’s a program with one slow part and one fast part:

from std.math import sqrt
def slow_part(n: Int) -> Float64:
var s: Float64 = 0
for i in range(n):
s += sqrt(Float64(i))
return s
def fast_part(n: Int) -> Int:
var s = 0
for i in range(n):
s += i % 7
return s
def main():
print(slow_part(3_000_000))
print(fast_part(1_000_000))

Output:

3464100748.904463
2999997

On Linux, we tried Valgrind’s callgrind tool on our test machine. Save the program as prof.mojo, then:

Terminal window
mojo build -g prof.mojo -o prof
valgrind --tool=callgrind --callgrind-out-file=cg.out ./prof
callgrind_annotate --auto=yes cg.out

Among a lot of other output, you’ll see something like this for your own file:

-- Auto-annotated source: prof.mojo
6,000,000 (14.63%) for i in range(n):
6,000,000 (14.63%) s += sqrt(Float64(i))
4,000,000 ( 9.76%) for i in range(n):
10,000,000 (24.39%) s += i % 7

The numbers are machine instructions per line, not seconds, but they point you at the busy lines. Two things to know:

  • Valgrind runs your program many times slower than normal, so use a smaller input than usual.
  • Small functions get inlined into their callers, so the function list may show everything inside main. The per-line view above still works.

Other options: perf on Linux (perf record ./prof, then perf report) and Instruments on macOS work on any executable with debug info too, but we haven’t tested them with Mojo, so check their own docs. The Mojo debugging lesson covers -g and the debugger.

This function makes a full copy of the list on every call. Change it so no copy is needed, and call it without .copy().

def largest(var xs: List[Int]) -> Int:
var best = xs[0]
for x in xs:
if x > best:
best = x
return best
def main():
var data: List[Int] = [4, 17, 9, 23, 8]
print(largest(data.copy()))
print(len(data))

Hint: does largest change the list or keep it? If not, it doesn’t need to own it.

Show solution
def largest(xs: List[Int]) -> Int:
var best = xs[0]
for x in xs:
if x > best:
best = x
return best
def main():
var data: List[Int] = [4, 17, 9, 23, 8]
print(largest(data))
print(len(data))

Output:

23
5

Without var, largest reads the list in place through a read-only reference. data is still yours afterwards, and nothing was copied.

Write squares(n: Int) -> List[Int] that returns the squares of 0 to n-1, reserving the right capacity first. Print squares(6).

Hint: List[Int](capacity=n), then append in a loop, and return xs^ at the end.

Show solution
def squares(n: Int) -> List[Int]:
var xs = List[Int](capacity=n)
for i in range(n):
xs.append(i * i)
return xs^
def main():
print(squares(6))

Output:

[0, 1, 4, 9, 16, 25]

The list makes room for n items once, so append never has to grow it. return xs^ moves the list out of the function instead of copying it.

  • Measure first, change one thing at a time, and keep results identical while you speed things up.
  • Arguments are read-only references by default: no copy. Mojo makes every copy of a List explicit (.copy()); prefer the default, or move with ^.
  • Reserve capacity with List(capacity=n) when you know the size. On our test machine that was roughly 2.5 to 3 times faster for a million appends.
  • Pick types on purpose: Int for indexes, Float32 when 7 digits are enough, small types for small data, and no mixing in hot loops.
  • Go step by step: better approach, habits, vectorize, parallelize, measuring each time.
  • Find the slow lines with a profiler on a mojo build -g executable, for example Valgrind’s callgrind on Linux.

Next up: Mojo and Python, how Mojo code can call Python and use its libraries.

Quick check

1. You pass a big List to def f(xs: List[Int]). What does that cost?
2. What does List[Int](capacity=1000) do?
3. Why can switching from Float64 to Float32 speed up vectorized math?
4. Why build with -g before profiling?