Allocations when moving loop into a function

omicron8
Sun, 01 Jun 2025 18:19:23 +0000
New to Julia

Why does the first variant (function foo) allocate a large amount of memory while the second variant (function bar) does not? The difference is whether the loop is inside or outside the function. Is there a way to have the loop outside without so many allocations?

using BenchmarkTools

function foo!(F, A)
  F[1] = A[2]
  F[2] = - A[1]
  return nothing
end

function bar!(F, A)
  for i = 1:size(A,1)
    F[i,1] = A[i,2]
    F[i,2] = -A[i,1]
  end
  return nothing
end

n = 15_000
A = rand(n,2)
F = similar(A)

@btime begin
  for i = 1:n
    @views foo!((F[i, :]), (A[i, :]))
  end
end

@btime begin
  bar!(F, A)
end

Reults:
6.409 ms (161935 allocations: 3.62 MiB)
4.062 μs (0 allocations: 0 bytes)

4 posts - 3 participants