Why serialize heap data to stable memory?

I have seen a lot of examples and posts having to do with serializing data to stable memory. In what scenario would I want to use a heap memory data structure and then have to serialize the data to stable memory vs just using a stable memory data structure from the start and not have to worry about serialization?

In all scenarios where you want to minimise cycle cost. Because using stable memory is likely many times more expensive. That is (a) due to accessing stable memory itself is much more costly, and (b) because an application or the Motoko runtime has much more severe constraints in organising data layout in stable memory and keeping its format forward/backward-compatible. (The former may improve in future versions of the IC, whereas the latter won’t.)

Think about it as akin to memory vs file system in a conventional computer, where you ask: In what scenario would I want to use memory for data and then have to store it to a file vs just using a file and reading every byte from there all the time?

2 Likes