# Motoko, Array, Memory

**URL:** <https://forum.dfinity.org/t/motoko-array-memory/5324>\
**Category:** Programs & Applications\
**Created:** [June 18, 2021, 11:16am UTC](https://forum.dfinity.org/t/motoko-array-memory/5324 "2021-06-18T11:16:42Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![rossberg](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/rossberg/32/795_2.png) [@rossberg](https://forum.dfinity.org/u/rossberg)\
**Post date:** [June 18, 2021, 1:00pm UTC](https://forum.dfinity.org/t/motoko-array-memory/5324/5 "2021-06-18T13:00:28Z")

</div>

First of all, let me point out that constructing an array by repeated concatenation is not something you should do in production code. Since both operands need to be copied for each append, the cost of doing this is quadratic in the size of the final array.

Assuming you want an immutable array, a more appropriate way is to create the complete array as mutable, initialise it via mutation, and then freeze it.

As for the `rts` values: `memory_size` is the current size of the Wasm memory array (mostly the same as the canister memory size). This can only grow, never shrink in Wasm, even if most of it is unused. However, unused/unmodified canister memory ought to have no cost on the IC.

The other values come from [here](https://github.com/dfinity/motoko/blob/2aa5073364b43769309d4358281ce2dadb66d90e/rts/motoko-rts/src/gc.rs). The two interesting ones are probably `heap_size`, which contains the actual size of the current Motoko heap, i.e., the heap memory in use, and `max_live_size`, which is the largest heap size that has remained so far after a GC. The other numbers are accumulative total bytes allocated and collected so far, which probably is less interesting.

So your program really only uses 40K of live memory in the end. (An immutable array takes up 4 bytes per element.)

Edit: But the 200M intermediate memory size are a consequence of your loop and its quadratic cost. Before Motoko gets to run GC, you are allocating 10\_000 arrays, with an average size of 5000 elements, i.e., 20K bytes. So the heap grew to 20K \* 10\_000 = 200M before GC happened at the end of the message. And of course you are paying for this temporary memory usage, just as for the cycles all the copying costs.

---

_[View the full topic](https://forum.dfinity.org/t/motoko-array-memory/5324)._
