moxzi
Docs / CLI / Writing fast Motoko

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.

fast.mo
// 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:

LoopCost 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.rangeabout 35-40
while (i < n) { …; i += 1 } with a Nat64 counterabout 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#

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.

fast.mo
// 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#

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.

On this pageMeasure firstLoopsNumbersBytesAllocationCryptography and big numbers