Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid memory allocation when using vcat in julia

Tags:

julia

Is there a way to avoid memory allocation when concatenating arrays in julia? For example,

const x = [1.0,2.0,3.0]

I preallocate

y = zeros(3,3)

Then get new y

y = hcat(x,x,x)

BenchmarkTools.Trial:
memory estimate:  256 bytes
allocs estimate:  4
--------------
minimum time:     62.441 ns (0.00% GC)
median time:      68.445 ns (0.00% GC)
mean time:        98.795 ns (18.76% GC)
maximum time:     40.485 μs (99.71% GC)
--------------
samples:          10000
evals/sample:     987

So how can I avoid allocation?

like image 741
JianghuiDu Avatar asked Apr 18 '26 04:04

JianghuiDu


1 Answers

julia> using BenchmarkTools

julia> const y = zeros(3,3);

julia> const x = [1.0,2.0,3.0];

julia> @benchmark y[1:3,:] .= x
BenchmarkTools.Trial:
  memory estimate:  64 bytes
  allocs estimate:  1
  --------------
  minimum time:     17.066 ns (0.00% GC)
  median time:      20.480 ns (0.00% GC)
  mean time:        30.749 ns (24.95% GC)
  maximum time:     38.536 μs (99.93% GC)
  --------------
  samples:          10000
  evals/sample:     1000

julia> y
3×3 Array{Float64,2}:
 1.0  1.0  1.0
 2.0  2.0  2.0
 3.0  3.0  3.0

Or you could iterate over rows - for a single row call no allocation will be made:

julia> @benchmark y[1,:] = x
BenchmarkTools.Trial:
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     12.373 ns (0.00% GC)
  median time:      12.800 ns (0.00% GC)
  mean time:        13.468 ns (0.00% GC)
  maximum time:     197.547 ns (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     1000
like image 180
Przemyslaw Szufel Avatar answered Apr 19 '26 16:04

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!