Garbage collection in Motoko

As Motoko is a language with a garbage collector - how does the GC determine when to execute?

From current observations (sample application below, and liberal use of dfx call and htop :P) it seems to only run between invocations of public functions, and never during - even if the amount of piled up garbage causes the call to abort due to exceeding what I assume is the WASM container exceeding its 4GB memory limit (Canister ... trapped: heap out of bounds).

Is this observation correct, or was memory allocation in this case simply too fast for the GC to keep up? The lack of a ‘sleep’ command didn’t allow me to test that hypothesis.

import Array "mo:base/Array";
import Iter "mo:base/Iter";

actor {
  public query func gcTest() : async () {
    // 1000 arrays of 1MB each for a total of 1GB memory
    for (i in Iter.range(1, 1_000)) {
      allocArray();
    };
  };

  func allocArray() {
    // Each one of these will be 1MB
    var ary : [var Word8] = Array.init<Word8>(1_000_000, 0xFF);
  };
};
4 Likes

You are right. Currently we only GC at the end of the message. This may change in the future though.

4 Likes

Thanks, good to have confirmation. :slight_smile:

1 Like