JM

Table of Contents

Views

We have seen that allocating memory on the heap can negatively impact performance, but what if we already have allocated memory, and simply want a convenient way to look at a part of an array, without increasing code complexity. This is where the view comes in handy. If you have used Python or MATLAB, you will be familiar with slicing syntax:

julia
a = rand(3,3)
b = a[1:2, 1:2]

This syntax, allows us to take a section of an array and manipulate it. The only issue is that we have just created a copy of that part of the array! To prove this, let’s mutate part of b and then look at the values of a:

julia
b .= 0
a

Notice that a is unchanged. This is a good behaviour by default, as if any other behaviour were implemented, this would lead to countless bugs. It is important to remember that simply assigning a variable to an array, will assign by reference and hence not make a copy, since the array variable is simply a pointer to the start of the array:

julia
c = a; # c and a point to the same memory now

However, if we want to mutate part of an array, while not copying the memory, we can just use a view. There is a handy macro that does this for us. Take the first example using the @views macro:

julia
a = rand(3,3)  # Reset a
b = @views a[1:2, 1:2]

Now, b points to the same four elements in memory as the top-left square of a. To show this, let’s manipulate b and check a:

julia
b .= 0
a

Notice that we have propagated this information back to a. This can be very useful when one would like to avoid making copies of arrays, but needs to access only part of the array.

Note: One should still be very careful, since the memory layout has not changed, but the indexing scheme has changed. This means that even though one may loop through the view using the correct indexing scheme, it is likely that the memory is not contiguous and hence can have severe performance penalties for using a view. In situations where memory locality is more impactful than allocating memory, a copy may be worth making. Again, this trade-off comes down to benchmarking, necessary for making an informed decision.