# Array memory allocation

I have a couple questions about Arrays.

If I do

``````A = [1, 2, 3]
B = [4, 5, 6]

M = [A, B]

A = 0
``````

I can see that the first vector in M has been changed to [0, 2, 3]. So from this I gather that M is actually storing pointers to the Vectors A and B.

Now I want to add another vector to M.

``````push!(M, [10, 11, 12])
``````

What is Julia doing here? Is it adding another pointer to M, kinda like a LinkedList in Java? Or is it remaking all of M?

If M gets very large, is this an efficient way of adding more vectors to M?

(I want to stick with an Array of Arrays because I like being able to pop! and push! them efficiently.)

On a similar note, when I say A = 0, is Julia modifying the existing array A, or is it rewriting the whole thing?

you are correct that in your first block of code, creates a vector of pointers. when you push a new vector to this, the vector is constructed, and if the vector is not at capacity, the pointer to that vector will be written after the current last index. If, however, there is not room in the vector, a new vector will be allocated, the contents of `M` (pointers to arrays) will be copied over. Since `push!` resizes by a factor of 2, this will remain relatively efficient even as `M` gets large (1/nth of the time, the vector will grow by n elements). To be more efficient, if you know how much you are adding, you can preallocate a vector of the correct size. When you say `A=0` Julia is taking the first element and replacing it with 0. This is a modification, and if the first element was an array for example, that array will not be deleted or modified. Just the pointer in the outer array will change.

2 Likes

Just to make sure I have this right, in the code above:

`A = 0` modifies A by rewriting over the existing memory containing the vector A.

`M = [5, 5, 5]` modifies M by creating a the new vector `[5, 5, 5]`, and replacing the pointer that pointed to B with one that points to this new vector. Furthermore, the old vector `[4, 5, 6]` is still taking up space.

Is this correct?

Is the reason `[4, 5, 6]` is still taking up space because the variable B is pointing to it? If I were to say `B = 6`, would the vector `[4, 5, 6]` still be there taking up space?

It would be there until garbage collection was run, which will happen eventually.

2 Likes