Please tell me everything practical about stable memory

Hi Matthias,

Sorry about the delay - hadn’t checked the forum due to travel.

I’ll keep it brief because I’ve got covid.

The ExperimentalStableMemory library has size : () -> Nat64 function that tells you the logical number of 64KiB IC stable memory pages allocated to ExperimentalStableMemory.

Because Motoko stable variables are also serialized to IC stable memory, after an upgrade, your canister may actually use more pages than the logical page count. I don’t think we expose the real page count at the moment, but could.

You can calculate the bytes of stable memory occupied by stable variables using function:

When called, it returns a query, that, when called, does the first part of an upgrade to determine how many bytes of stable memory are required for the upgrade, without actually doing the upgrade or serializing the data. Since it’s a query, the state changes are discarded so executing the query has no effect but tells you much data would be required.

The actual number of physical stable memory pages used may be 1 page more than the sum of ExperimentalMemory.size() and stable variables bytes + 65535 / 65536. The additional page may be needed to store some small, finite size metadata describing the layout of this data so it can be restored on upgrade.