Is there any document about the amount of memory occupied by the basic types of Motoko canister?

Is there any document about the amount of memory occupied by the basic types of Motoko canister?

such as a Nat8 array with n size, a principal, a enum, a HashMap and so on.

2 Likes

In the world of canisters and cycles… every byte counts.

No, I don’t think such a document exists. The ASCII-art and comments in motoko/compile.ml at master · dfinity/motoko · GitHub is maybe the best place right now, but this is of course written with the compiler developer in mind. And there are a bunch of optimizations (e.g. small numbers are not stored as pointed-to objects, but “instead of” the pointer) that make such predictions harder.

To answer your concrete questions:

  • A [Nat8] with n elements will take 8+4×n bytes.
  • A principal is represented the same way as a blog, so if it is n bytes (binary representation, not the textual format), then up to 8+n+3 bytes.
  • An variant is 12 bytes (plus whatever is stored inside the tag). If it’s strictly an enum (i.e. only () stored inside), then the () is “free”.
  • A hashmap is more complicated, but it’s not a basic type, so I’ll punt on that one :slight_smile:
2 Likes

Thanks for your great answer,

How about Nat32, Nat64, Nat, Int, Text, List, Option ?T, Char

  • Nat32, Char: 8 bytes
  • Int64: 12 bytes
  • Nat and Int: “free” if smaller than 2^30, else at least 20 bytes, up to arbitrary sizes
  • Text and Blob: up to 8+n+3 bytes.
  • opt: “free” unless you deal with the value ?…?null
  • List is not a basic type. Probably 12*n

Free means that it’s stored inside the containing data structure without extra allocation.

4 Likes