Since to (almost. Which not?) All the effects the following two assignments are equivalent, why, since view is faster and cheaper, is not [ ] (ie getindex) defined in the same way?
a=[1,2,3]
b=a[1:2]
b=view(a, 1:2)
If the explanation isn’t too laborious, in this simple case, I’d like to know what view() does differently than getindex() to be faster and not allocate.
You can see the difference between getindex and view when mutating an element of b:
julia> a = [1, 2, 3];
julia> b = a[1:2]
2-element Vector{Int64}:
1
2
julia> c = view(a, 1:2)
2-element view(::Vector{Int64}, 1:2) with eltype Int64:
1
2
julia> b[1] = 4
4
julia> a # Data in a is unchanged
3-element Vector{Int64}:
1
2
3
julia> c[1] = 4
4
julia> a # Data in a has changed as well
3-element Vector{Int64}:
4
2
3
Thus, getindex will take the values from the slice and copy it into a new array. In contrast, view just wraps the original array and indexes into it. Thereby, getindex is safer to use, i.e., as it cannot change the data it has been taken from, whereas view is faster as it does not need to copy.
I had an unclear idea that this was the main difference. This is why I tried to make tests similar to those you illustrated, but, for some mess I made, I found the same result in both cases …