Convert array into matrix in place

reshape is in-place:

julia> v = rand(10^6);

julia> using BenchmarkTools

julia> @btime reshape($v, 1000,1000);
  42.719 ns (2 allocations: 96 bytes)

Notice that the allocation here is quite small and is essentially just a wrapper object.

You can actually use an explicit wrapper object of type Base.ReshapedArray with some undocumented internals:

julia> reshape2(v, dims) = Base.__reshape((v,IndexLinear()), (1000,1000))
reshape2 (generic function with 1 method)

julia> v = rand(10^6);

julia> @btime reshape2($v, (1000,1000));
  2.034 ns (0 allocations: 0 bytes)

(Beware that the above reshape2 function doesn’t do any argument checking, e.g. it doesn’t check whether the sizes are compatible.)

See also the discussion in reshape(::Array, ...) is slow and allocates · Issue #36313 · JuliaLang/julia · GitHub

2 Likes