# Removing allocations from ForwardDiff.jacobian!

**URL:** https://discourse.julialang.org/t/removing-allocations-from-forwarddiff-jacobian/80996
**Category:** General Usage
**Tags:** memory-allocation, forwarddiff
**Created:** [May 13, 2022, 5:24am UTC](https://discourse.julialang.org/t/removing-allocations-from-forwarddiff-jacobian/80996 "2022-05-13T05:24:19Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![jbu](https://avatars.discourse-cdn.com/v4/letter/j/a8b319/32.png) [@jbu](https://discourse.julialang.org/u/jbu)
#### Post date: [May 13, 2022, 5:24am UTC](https://discourse.julialang.org/t/removing-allocations-from-forwarddiff-jacobian/80996/1 "2022-05-13T05:24:19Z")

</div>

I’m getting a few stray allocations while using `ForwardDiff.jacobian!`. I followed the advice in [this post](https://discourse.julialang.org/t/getting-forwarddiff-jacobian-to-execute-with-zero-allocations/72503), but that didn’t seem to remove them. What’s the best way to track down and eliminate these allocations?

_Edit: I’m using Julia v1.7.2. OS is Ubuntu 20.04._

MWE:

```julia
using ForwardDiff, BenchmarkTools

# Functions
function func(dx,x)::Nothing
  @. dx = 2*x
  return nothing
end

function jac!(J,dx,x)::Nothing
  ForwardDiff.jacobian!(J,func,dx,x, ForwardDiff.JacobianConfig(func,dx,x,ForwardDiff.Chunk{10}()))
  return nothing
end

# Variables
dx = zeros(1000)
x = ones(1000)
J = zeros(1000,1000)

# Actual function calls
@btime func(dx,x) # Zero allocations

@btime jac!(J,dx,x) # Four allocations

```

---

<div class="post-metadata">

### Author: ![franckgaga](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/franckgaga/32/218241_2.png) [@franckgaga](https://discourse.julialang.org/u/franckgaga)
#### Post date: [December 18, 2024, 10:10pm UTC](https://discourse.julialang.org/t/removing-allocations-from-forwarddiff-jacobian/80996/2 "2024-12-18T22:10:18Z")

</div>

That’s because you are constructing the `JacobianConfig` object inside `jac!` function, thus re-allocating at each `jac!` call. This version does not allocate:

```julia
using ForwardDiff, BenchmarkTools

# Functions
function func(dx,x)::Nothing
  @. dx = 2*x
  return nothing
end

function jac!(J,dx,x,cfg)::Nothing
  ForwardDiff.jacobian!(J,func,dx,x,cfg)
  return nothing
end

# Variables
dx = zeros(1000)
x = ones(1000)
J = zeros(1000,1000)
# construct the JacobianConfig object in advance:
cfg = ForwardDiff.JacobianConfig(func,dx,x,ForwardDiff.Chunk{10}())

# Actual function calls
@btime func(dx,x) # Zero allocations

@btime jac!(J,dx,x,cfg) # Zero allocations now !!!

```
