In the matrix below, the first, second, and third columns represent the height, area, and volume of rectangular objects, respectively. I need to sort the items in non-ascending order of height (from the highest to the lowest). After sorting, the associated area and volume for each item should remain correctly aligned with its height.

βdoes not materializeβ means does not have to allocate memory and set it to these values, but the required values are calculated on the CPU from the inputs as needed. Basically, this is the advantage of views, which just tell the CPU where to find the original array and how to calculate a modified index into the original array.

BTW, on my machine, adding the missing @view, using stevengjβs style, benchmarks more than 5x the benchmark without the second @view:

Just note that this is not free. Each array access now requires an additional load. If you plan to access the sorted array a great number of times, then this additional cost might add up and you could come out slower.

julia> using BenchmarkTools; v = rand(1000); inds = rand(1:1000, 10000);
julia> @btime let s = 0, v = view($v, sortperm($v))
for i in $inds
s+= v[i]
end
s
end
72.009 ΞΌs (2 allocations: 15.88 KiB)
4971.880280956974
julia> @btime let s = 0, v = sort($v)
for i in $inds
s+= v[i]
end
s
end
58.389 ΞΌs (3 allocations: 18.06 KiB)
4971.880280956974

Interestingly enough if I directly interpolate the array/view then there is no runtime difference:

julia> @btime let s = 0
for i in $inds
s+= $(sort(v))[i]
end
s
end
39.392 ΞΌs (0 allocations: 0 bytes)
4971.880280956974
julia> @btime let s = 0
for i in $inds
s+= $(view(v,sortperm(v)))[i]
end
s
end
39.462 ΞΌs (0 allocations: 0 bytes)
4971.880280956974

If what is really needed is the operation on matrices, others have already provided their solutions. But I canβt resist to point out that if your matrix represents data with this column interpretation, you may want to consider using some higher-level data type for your data. Namely, DataFrame from DataFrames.jl package. Have a look how convenient and systematic this sorting of your table is: