Taking views of views allocate in Julia
Asked Answered
P

1

6

I noticed that taking views of non-"fast linear indexed" subarray allocates, while this is possible on classical vectors. Any idea, how to make this allocation free?

Here is an illustration of the behavior:

function temp!(lin::Vector{Int}, v::AbstractVector)
  w = view(v, lin)
  return nothing
end

lin = Int[1]; v = [0.0, 0.0, 0.0, 0.0];
temp!(lin, v)
@allocated temp!(lin, v) # allocates 0
vr = view(v, 1:3)
temp!(lin, vr)
@allocated temp!(lin, vr) # allocates 64
Polaris answered 20/12, 2022 at 15:14 Comment(1)
I do not think it is in general possible.Gabion
J
2

view(x, v) directly refers to the memory location of v when x is a vector (not a view), e.g.

x=[1,2,3]
v=Int[1]
y=view(x,v)
print(y)
v[1]=2
print(y)

but Julia cannot directly use v when x is a view, because v has to be reindexed for x, so Julia needs to allocate v unless v is a Range which doesn't need any allocation.

Jugulate answered 22/12, 2022 at 4:7 Comment(1)
So, is there a workaround for getting a view of a view in a non-allocating manner?Faveolate

© 2022 - 2024 — McMap. All rights reserved.