Generating a sparse matrix from scratch seems to be quite memory intensive. and slow. Say I wish to create a large block diagonal matrix with 2x2 block entries.
Doing it naively is quite slow function f(k) M = spzeros(2*k,2*k) for i = 1:k D = (i-1)*2 + 1:i*2 M[D,D] = randn(2,2) end return M end julia> @time f(10000) 2.534277 seconds (239.26 k allocations: 3.013 GB, 15.58% gc time) Is there a way to speed this up by preallocating the memory somehow?