How do I convert a matrix to an array of tuples while avoiding many small allocations in a loop? My current code is
function matrixtotuple(x::AbstractMatrix{T}) where T
r,c = size(x)
pts = Vector{Tuple}(undef,r)
@time @inbounds for i in 1:r
pts[i] = Tuple(x[i,:])
end
return pts
end
For a 20x2 matrix, the loop does 100 allocations which means its 5 allocations per row. For a large matrix with millions of entries, it will perform many small allocations thus slowing down my code. Is there a better way to do this operation without allocating in the loop?
With StructArrays you could create a custom array type such that indexing into it gives you tuples, while reusing memory, which can be useful if the original array is big: