logo

How to Quickly Reference Subarrays in Julia 📂Julia

How to Quickly Reference Subarrays in Julia

Overview

In Julia, view is a data structure that quickly refers to a subarray of an array, making it seem cumbersome from a user’s perspective, although there might seem to be no difference. However, it returns a lighter array as it is lazily referenced. Therefore, in Julia code that is optimized even at a very basic level, it is easy to find the macro @views.

Code

Let’s refer to a submatrix of the matrix M.

Functional form: view()

view(A, inds...)

  • Returns a view according to inds... of A.

However, this form is generally not preferred as it makes the code harder to read. By using the following macro, view can be used without much difference from the basic Julia syntax.

Macro: @view

The @view macro changes the context of the code referring to subarrays as if view has been applied.

Apply to the entire block: @views

The @views macro applies @view to the entire following block. Thanks to this, simply adding @views like @views f(x) ... end in front of a function written comfortably without view automatically applies view.

Full Code

Speed Comparison

fcopy() and fview() are functions that perform exactly the same function but differ in speed. At a glance, the speeds seem similar, but most of it is compilation time. Excluding this and comparing only the simple execution time, there is about a 4-times difference.

Environment

  • OS: Windows
  • julia: v1.7.0