 # Assign values to a subarray and it take a long time and large allocation

I have functions such as

``````function max_(v::Matrix{Float64})
m,idx=findmax(v,dims=2)
Dt=vec(getindex.(idx,2))
return m,Dt
end

function max_!(Vs::AbstractVector{Float64},Ds::AbstractVector{Float64},v::Matrix{Float64})
Vs,idx=findmax(v,dims=2)
Ds=vec(getindex.(idx,2))
end
``````

I run this

``````mat=[[1,2.,3] [4.,5,6] [1.,2.,3.]]

Vs=zeros(3,3);Ds=zeros(3,3);

@time max_!((@view Vs[:,1]),(@view Ds[:,1]),mat)
``````

It takes

0.057112 seconds (154.04 k allocations: 8.670 MiB, 99.92% compilation time)

and

then run this

``````@time Vs[:,1],Ds[:,1]=max_(mat)
``````

It takes

0.037935 seconds (34.87 k allocations: 1.926 MiB, 99.73% compilation time)

If I try

``````@time V,D=max_(mat)
``````

I get

0.000014 seconds (10 allocations: 528 bytes)

How could that be? Why is it so low to give values to a subarray?

you’re measuring compilation time, mostly EDIT: second run here takes

``````julia> @time max_!((@view Vs[:,1]),(@view Ds[:,1]),mat);
0.000022 seconds (14 allocations: 656 bytes)
``````

My bad, sorry! Contribute a meaningless question ::

These are perhaps just toy functions, but note that `max_!` does not modify the `Vs` and `Ds` input arguments. You need `Ds .= vec` for that.

1 Like

I did not know .= do necessary to change the value. Thank you for reminding! And these are toy functions.