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.

6 Likes

Does this also apply to the RUST canister?

No, he’s talking about Motoko only.

Just curious: why does a Nat32 occupy 8 bytes?

Every heap-allocated object has a 1-word (4-bytes) header, followed by the payload, which, in this case, is 4 bytes:

1 Like

Does it specific only for motoko compiled module? I mean if I build a module using rust what size whould be for byte array ?