Writing fast Motokoalpha
Measure what your code costs in instructions, and the loop, number and library choices that keep it low.
On the Internet Computer every WebAssembly instruction your actor executes is billed, and each message has an instruction limit. Nothing optimizes your code again at run time, so the shape of your code shows up directly in the bill. This page shows how to measure what a piece of code costs and which choices make the biggest difference.
Measure first#
InternetComputer.countInstructions from core runs a function and returns the instructions it took. Measure inside the message you care about, since the counter restarts at the start of every message and after every await.
// The instructions a loop of `n` empty iterations costs, written three ways.
public query func loops(n : Nat) : async { whileNat : Nat64; range : Nat64; whileNat64 : Nat64 } {
let whileNat = InternetComputer.countInstructions(func() {
var i = 0;
while (i < n) { i += 1 };
});
let range = InternetComputer.countInstructions(func() {
for (_ in Nat.range(0, n)) {};
});
let m = n.toNat64();
let whileNat64 = InternetComputer.countInstructions(func() {
var i : Nat64 = 0;
while (i < m) { i += 1 };
});
{ whileNat; range; whileNat64 };
};
To get real counts from a local server, start moxzid with MOXZI_FUEL=1. Without it the counter only advances by a fixed step per call, which is enough for code that checks a budget but not for measuring.
MOXZI_FUEL=1 moxzid -m actors.json
curl -s -w '\n' -d '[1000]' http://127.0.0.1:7000/query-json/fast/loops
curl -s -w '\n' -d '[2000]' http://127.0.0.1:7000/query-json/fast/loops
[{"range":33034,"whileNat":33033,"whileNat64":29028}]
[{"range":66034,"whileNat":66033,"whileNat64":58028}]
The numbers grow with n, so compare two sizes and divide the difference by the change in n. That cancels the fixed cost of the call. Here each iteration costs about 33 instructions with a Nat counter and about 29 with a Nat64 counter. On the Internet Computer the same code costs a little more, because the replica counts some instructions differently, but the comparisons hold.
Loops#
These forms compile to a counted loop, with no iterator object and no closure call per step:
| Loop | Cost per iteration |
|---|---|
for (x in array.values()), array.keys() | about 15-30 |
for (b in blob.values()), blob.keys() | about 25-30 |
for (i in Nat.range(a, b)), Nat.rangeInclusive, Int.range | about 35-40 |
while (i < n) { …; i += 1 } with a Nat64 counter | about 30 |
for (c in text.chars()) | about 45-80 per character |
Anything else that produces an iterator, such as Iter.map, a map's entries() or your own { next } object, calls a closure for every element. That costs 100 to 200 instructions per step before the loop body does any work. In a hot loop, iterate over the underlying array or blob instead.
Numbers#
NatandIntare fast below 2^61. Values below that, negativeInts included, add, subtract, multiply, divide and compare in a few instructions. Larger values become heap bignums, and every operation on them calls into the runtime: thousands of instructions for a 256-bit multiply, hundreds of thousands for a division of a 3,000-bit number.- Use
Nat64for counters, indices and hashing state when you know the range. It never allocates and never changes representation. - Prefer
Nat64for bit manipulation. Shifts, rotations,^and wrapping arithmetic (+%,*%) onNat64are one or two instructions.Nat32and smaller types cost a few more, because they keep their value in the upper half of a 64-bit word. Shift and rotate by a constant where you can: the compiler folds the amount. - Put constants at module level.
let MASK : Nat64 = 0xFFFF_FFFFand constant arrays are compiled once, and a loop reads them from a local after the first iteration.
Bytes#
Process a Blob with for (b in blob.values()) or by indexing it. Converting bytes with b.toNat32() and similar conversions compiles to the conversion itself, not a function call.
// A rolling checksum over `n` bytes, and the instructions the loop took.
public query func checksum(n : Nat) : async { sum : Nat32; instructions : Nat64 } {
let data = Array.tabulate<Nat8>(n, func i = Nat8.fromIntWrap(i)).toBlob();
var sum : Nat32 = 0;
let instructions = InternetComputer.countInstructions(func() {
for (byte in data.values()) {
sum := (sum <<> 5) ^ byte.toNat32();
};
});
{ sum; instructions };
};
curl -s -w '\n' -d '[1000]' http://127.0.0.1:7000/query-json/fast/checksum
[{"instructions":52032,"sum":1425845852}]
That loop costs about 50 instructions per byte, most of it the rotate and the xor on a Nat32.
Allocation#
- Don't grow an array in a loop.
Array.concatand.concatcopy both arrays, so appending one element at a time is quadratic. Collect into aListor aVarArrayof known size, and convert once at the end. - Spread large writes over several messages. So that it can undo a trap,
moxzidsaves each memory page a message writes before the message changes it. A message that changes a few pages stays fast however large the actor is. A message that rewrites most of a large memory, for example by building a big temporary value, pays for every page.
Cryptography and big numbers#
Elliptic curves, pairings and RSA written in Motoko spend nearly all their time in bignum arithmetic, and run 10 to 60 times slower than native code. Use the native kernels for secp256k1, P-256, Ed25519, BLS12-381, RSA and the SHA-2 family. Hash functions written in plain Motoko over Nat32 or Nat64 words are reasonable: CRC-32 costs about 75 instructions per byte and the sha2 package's SHA-256 about 220.